const util = require('../../../../../../utils/util.js');
const utilTime = require('../../../../../../utils/time.js');
const api = require('../../../../../../config/api.js');
const user = require('../../../../../../services/user.js');
const recorderManager = wx.getRecorderManager();
var recordInterval = null;

//获取应用实例
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    photoDialogShow: false,
    maxCommission: 0,
    shareInfo: { "shareImageDialogShow": false, "shareImage": "", "circleid": "" },// 分享的图片信息
    openStoreInfo: {},// 开通店铺的信息
    openStoreDialogShow: false,
    preferentialOpenStoreDialogShow: false,//开通店铺的弹窗
    exitCircleDialogShow: false,// 圈主退出圈子的弹窗
    exitCircleDialogShow2: false,// 用户退出圈子的弹窗
    clockData: {},// 打卡数据
    thirdHeight: 0,//.thirdHeight的高度
    mainBasHomeinfo: {},//圈主的主页信息
    seedDialog: { "show": false, "index": "", "seedRulesDialogShow": false, "diaryInfo": {} },
    chengbeiDialog: { "show": false, "size": 0, "count": 0, "shareDialogShow": false },// 分享赚橙贝的弹窗
    circleRecommendPageNum: 1,// 推荐信息的页数
    circleRecommendPageSize: 10,// 推荐信息的页大小
    circleRecommendList: [],//推荐信息
    isCircleRecommendQuery: true,// 是否可以请求推荐信息：用于下拉获取更多
    energySize: '',// 能量的数量
    audioOauhRefusedDialogShow: false,// 语音拒绝授权的弹窗
    otherPageIndex: '',// 去其他页面的日记下标
    commentsDialogShow: false,//评论的弹窗
    deleteDiaryDialogShow: false,//删除日记的弹窗
    updateGroupid: '',// 需要修改的分组id
    loadOptions: {},// onload时的数据
    groupingDialogShow: false,// 有分组的弹窗
    groupingEmptyDialogShow: false, // 无分组的弹窗
    groupList: [],// 分组的数据
    interestJoinPageNum: 1, // 组员的页数
    interestJoinPageSize: 10, // 组员的每页大小数
    interestJoinTotalPages: 0,// 组员的总页数
    interestJoinTotalCount: 0,// 组员的总数量
    interestJoinList: [],// 组员数据
    screeningData: { "isreview": "", "members": "", "starttimevalue": "", "starttimetext": "选择开始时间", "starttimearray": [0, 0, 0], "endtimevalue": "", "endtimetext": "选择结束时间", "startendarray": [0, 0, 0], "groupid": "", "endTimePickerDisabled": false, "startTimePickerDisabled": false, "select_openid": "" },// 筛选条件里的数据
    screeningDialogShow: false,// 选择筛选的弹窗
    login_code: "",// 登录时的code
    authPhoneDialogShow: false,// 验证手机号提示的弹窗
    diaryOperationShow: false,// 日记操作的底部显示
    diaryOperationShowInfo: {},// 日记操作的主要数据信息
    diaryCommentsid: '',// 评论的id
    isCommonsDelete: false,// 是否显示评论的删除
    commonsBottomShow: false,// 评论的底部是否显示
    saveCommentsIndex: '',//提交评论的日记下标
    diary_commones_dialog: false,// 评论回复成功之后的弹窗
    mainReplyCommentsid: 0,// 评论回复的主id
    replyCommentNickname: '',// 被评论回复的昵称
    replyCommentsid: 0,// 评论回复的id
    commentsTextarea: '',// 评论的texteare
    commentsAudio: {},// 评论的语音
    diary_givelike_dialog: false,// 点赞成功之后的弹窗
    reviewBottomDeleteShow: false,// 删除点评的确定弹窗
    ordReviewId: '',//点评id
    reviewBottomEditorAndDeleteIsShow: false, // 点评底部弹出时是否显示编辑和删除
    reviewBottomIndex: '',// 点评底部弹出时的日记的index
    reviewBottomYIndex: '',// 点评底部弹出时的点评的index
    reviewBottomShow: false,// 点评底部的的弹出显示
    diary_review_dialog: false,// 点评成功之后的弹窗
    isSubmitAll: false,// 是否正在发布点评
    ordReviewQuickTextLength: 0,// 快捷语的texteare的长度
    ordReviewQuickText: '',// 快捷语的texteare
    ordReviewQuickId: '',// 快捷语的id
    selectReviewQuickIndex: "", //快捷评语选中的下标
    reviewQuickList: [],// 快捷评语数据
    quickLanguageShow: false, // 添加快捷语的弹窗显示
    quickLanguageBottomShow: false, // 快捷语底部的的弹出显示
    isClock: false,// 控制是否可以打卡
    reviewImageList: { "imageList": [{ "clickNumber": 0 }, { "clickNumber": 0 }, { "clickNumber": 0 }, { "clickNumber": 0 }, { "clickNumber": 0 }], "totalScore": 0 },// 点评的分数
    reviewDialogShow: false,// 控制点评的弹窗显示
    review_diary: {},// 正在点评的日记信息
    diary_energy_dialog: false,// 打卡成功之后的弹窗
    thisInterestJoinUser: {},// 当前用户在圈子中的角色信息
    mainUserSetup: {},// 圈主的基本设置信息
    diaryInfoList: [],// 日记信息
    diaryInfoPageNum: 1, // 日记详情的页数
    diaryInfoPageSize: 10, // 日记详情的每页大小数
    diaryInfoTotalPages: 0,// 日记详情的总页数
    ordInterestJoinCount: 0,// 参与数量
    collectionUserCount: 0,// 自己对此圈子收藏数量
    collectionTotalCount: 0,// 圈子总收藏数量
    diaryCount: 0,// 日记数量
    allCententCheckedIndex: 1, // 选中下标（1日记  2详情  3目录  4成员）
    announcementTextareaDisabled: true,// 公告栏的Textarea是否禁用
    announcementShow: false, // 公告栏的弹窗
    collectionShow: false,// 收藏时的弹窗
    cancelCollectionShow: false,// 取消收藏时的弹窗
    albumInfo: [],// 圈子【图片、文字、音频】详情信息
    mainUser: {},// 圈主信息
    ordContractList: [],//契约信息
    ordInterest: {},// 圈子详情
    circleid: "",// 圈子id
    reviewTextarea: "",//点评的textarea的值
    reviewTextareaShow: false,// 控制点评的textarea是否显示
    reviewAudio: {},// 点评的音频
    reviewImage: {},// 点评的图片
    pageCenterTopPositionFixed: "",// 页面滚动的时候，“日记、详情、目录、成员”要显示在顶部
    title: "",// 标题
    firstSteplayerShow: false,// 首次进入第一步框是否弹出
    secondSteplayerShow: false,// 首次进入第二步框是否弹出
    thirdSteplayerShow: false,// 首次进入第三步框是否弹出
    setShow: false,// 是否显示设置
    maskLayerShow: false,// 自定义遮罩层是否显示
    isHasContract: true,// 是否有契约
    isHasTheme: true,// 是否有主题
    screeningTimeArray: [],// 筛选的开始时间的数据
    select_groupid: '',// 查询的分组id
    select_openid: '',// 查询的openid
    jumpDiary: false,// 控制打卡完成后页面自动滚动到打卡信息
    themeInfo: {},// 主题
    circleOperationShow: false,
    circleOperationShow2: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var isOnShow = options.isOnShow;
    var _this = this;
    var circleid = options.circleid;
    var select_groupid = "";
    var select_openid = "";
    if (options.select_groupid != null && options.select_groupid.length > 0) {
      select_groupid = options.select_groupid;
    }
    if (options.select_openid != null && options.select_openid.length > 0) {
      select_openid = options.select_openid;
    }
    _this.setData({
      circleid: circleid,
      ["screeningData.groupid"]: select_groupid,
      ["screeningData.select_openid"]: select_openid,
      loadOptions: options
    });
    var backgroundAudioManager = wx.getBackgroundAudioManager();
    wx.pauseBackgroundAudio();//暂停播放音乐
    backgroundAudioManager.pause();//暂停播放音乐

    if (!(isOnShow == true)) {
      // 获取圈子信息
      _this.getCircleDetails();
    }
    
    // 获取日记信息
    _this.getDiaryInfo();
    // 修改圈子的预览次数
    _this.addIspreview();

    // 获取三十天前的数据
    var screeningTimeArray = [];
    var day = utilTime.lastThirtyAllDay(30);
    var hours = utilTime.getAllHours();
    var minutes = utilTime.getAllMinutes();
    screeningTimeArray.push(day);
    screeningTimeArray.push(hours);
    screeningTimeArray.push(minutes);
    _this.setData({
      screeningTimeArray: screeningTimeArray
    })
  },

  /**
   * 获取圈子主题信息
   */
  getThemeAndGroupByCircle: function () {
    var _this = this;
    var circleid = _this.data.circleid;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.circleid = circleid;
        data.access_token = res.access_token;
        util.post(api.Interest_GetThemeAndGroupByCircleApi, data).then(function (res) {
          if (res.code == 200) {
            var result = res.result;
            _this.setData({
              themeInfo: result
            })
            _this.checkUserThemeClock(2);
          }
        })
      })
    }
  },

  /**
   * 进入主题管理
   */
  navigateToThemManage: function () {
    var _this = this;
    wx.navigateTo({
      url: "../../../../../../interest/pages/interest/theme/themManage/themManage?circleid=" + _this.data.circleid
    })
  },

  /**
   * 进入创建主题页面
   */
  navigateToCreateTheme: function () {
    var _this = this;
    var themeType = _this.data.ordInterest.themeType;
    if (themeType != null) {
      // 已经选择了类型
      wx.navigateTo({
        url: "../../../../../../interest/pages/interest/theme/makeTheme/makeTheme?o_type=create&type=" + themeType + "&circleid=" + _this.data.circleid
      })
    } else {
      wx.navigateTo({
        url: "../../../../../../interest/pages/interest/theme/themeIndex?circleid=" + _this.data.circleid
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var _this = this;
    var diary_energy_dialog = _this.data.diary_energy_dialog;
    if (diary_energy_dialog == true) {
      setTimeout(() => {
        _this.setData({
          diaryInfoList: [],
          interestJoinList: [],
          diary_energy_dialog: false,
          interestJoinPageNum: 1,
          interestJoinPageSize: 10,
          diaryInfoPageNum: 1,
          diaryInfoPageSize: 10,
        })
        var loadOptions = _this.data.loadOptions;
        loadOptions.isOnShow = true;
        _this.onLoad(loadOptions);
      }, 2000);
    }

    // 获取分组信息
    _this.getGroup();
    // 获取用户快捷评语
    _this.getOrdReviewQuick();

    /**
     * 从日记详情回来后，需要刷新当前日记
     */
    var otherPageIndex = _this.data.otherPageIndex;
    if (parseInt(otherPageIndex) >= 0) {
      _this.getDiaryInfoByDiaryId(otherPageIndex);
      _this.setData({
        otherPageIndex: ''
      })
    }


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var _this = this;
    var allCententCheckedIndex = _this.data.allCententCheckedIndex;
    if (allCententCheckedIndex == 1) {
      // 获取更多日记信息
      var diaryInfoPageNum = _this.data.diaryInfoPageNum;
      var diaryInfoTotalPages = _this.data.diaryInfoTotalPages;
      if (diaryInfoPageNum < diaryInfoTotalPages) {
        diaryInfoPageNum = diaryInfoPageNum + 1;
        _this.setData({
          diaryInfoPageNum: diaryInfoPageNum
        })
        _this.getDiaryInfo();
      }
    } else if (allCententCheckedIndex == 6) {
      // 猜你喜欢
      var isCircleRecommendQuery = _this.data.isCircleRecommendQuery;
      if (isCircleRecommendQuery) {
        _this.setData({
          circleRecommendPageNum: _this.data.circleRecommendPageNum + 1
        })
        _this.getCircleRecommendInfo();
      }
    } else if (allCententCheckedIndex == 3) {
      // 获取更多目录信息

    } else if (allCententCheckedIndex == 4) {
      // 获取更多成员信息
      var interestJoinPageNum = _this.data.interestJoinPageNum;
      var interestJoinPageSize = _this.data.interestJoinPageSize;
      var interestJoinTotalPages = _this.data.interestJoinTotalPages;

      if (interestJoinPageSize < interestJoinTotalPages) {
        interestJoinPageNum = interestJoinPageNum + 1;
        _this.setData({
          interestJoinPageNum: interestJoinPageNum
        })
        _this.getInterestJoin();
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    var _this = this;
    var id = _this.data.circleid;
    var ischeckshare = "";
    var type = "";
    var index = "";
    if (e.target != null && e.target.dataset != null) {
      type = e.target.dataset.type;
      index = e.target.dataset.index;
      ischeckshare = e.target.dataset.ischeckshare;
    }
    if (type == "2") {
      // 分享的是日记
      var diaryInfo = _this.data.diaryInfoList[index];
      var nickname = diaryInfo.diaryUserInfo.nickname;
      var imageVideoList = diaryInfo.imageVideoList;
      var imageUrl = _this.data.ordInterest.postersIp + _this.data.ordInterest.posterImageUrl;
      for (var i = 0; i < imageVideoList.length; i++) {
        if (imageVideoList[i].imageVideoType == "1") {
          imageUrl = imageVideoList[i].ip + imageVideoList[i].url;
          break;
        }
      }
      return {
        title: nickname + "的日记",
        path: 'pages/home/shareJump/shareJump?id=' + id + "&type=" + util.getShareType("diary") + "&isCheckLogin=1&circleid=" + _this.data.circleid,
        imageUrl: imageUrl
      }
    } else {
      var openid = app.globalData.logininfo.openid;
      var nickName = app.globalData.logininfo.userInfo.nickName;
      var title = nickName + "邀请你打卡#" + _this.data.ordInterest.title + "#";
      return {
        title: title,
        path: 'pages/home/shareJump/shareJump?id=' + id + "&type=" + util.getShareType("circle") + "&shareOpenid=" + openid + "&isCheckLogin=1"
      }
    }
  },

  /**
   * 授权手机号的弹窗
   */
  getPhoneNumber: function (e) {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    var code = _this.data.login_code;
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      // 未授权
      _this.authPhoneDialogClose();
    } else {
      // 同意授权
      var encryptedData = e.detail.encryptedData;
      var iv = e.detail.iv;
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.encryptedData = encryptedData;
        data.iv = iv;
        data.openid = openid;
        data.code = code;
        data.access_token = res.access_token;
        data.sessionkey = app.globalData.logininfo.sessionkey;
        util.post(api.Home_UpdateUserMobileApiUrl, data).then(function (res) {
          if (res.code == 200) {
            _this.authPhoneDialogClose();
          }
        })
      })
    }
  },

  /**
   * 监听屏幕滚动 判断上下滚动
   */
  onPageScroll: function (e) {
    var _this = this;
    var title = _this.data.title;
    var scrollTop = parseInt(e.scrollTop);
    if (scrollTop > 100) {
      //  设置标题
      wx.setNavigationBarTitle({
        title: title,
      });
    } else {
      //  设置标题
      wx.setNavigationBarTitle({
        title: '',
      });
    }
    var thirdHeight = _this.data.thirdHeight;
    if (thirdHeight == null || thirdHeight <= 0) {
      var query = wx.createSelectorQuery();
      query.select('.thirdHeight').boundingClientRect(function (rect) {
        _this.setData({
          thirdHeight: rect.height
        })
      }).exec();
    } else {
      if (scrollTop >= thirdHeight) {
        _this.setData({
          pageCenterTopPositionFixed: "positionFixed"
        })
      } else {
        _this.setData({
          pageCenterTopPositionFixed: ""
        })
      }
    }

  },

  /**
   * 筛选确定动作
   */
  screeningConfirm: function (e) {
    var _this = this;
    _this.setData({
      diaryInfoPageNum: 1,
      diaryInfoPageSize: 10,
      screeningDialogShow: false,
      diaryInfoList: []
    })
    _this.getDiaryInfo();
    //util.dialogAlert("没有符合条件的日记");
  },

  /**
   * 点评的textarea的焦点移入事件
   */
  reviewTextareaCheckYes: function (e) {
    var _this = this;
    var reviewTextareaShow = _this.data.reviewTextareaShow;
    _this.setData({
      reviewTextareaShow: true
    })
  },

  /**
   * 点评的textarea的焦点移出事件
   */
  reviewTextareaCheckNo: function (e) {
    var _this = this;
    var isSwitchEmoji = false;
    if (e.detail != null && e.detail.isSwitchEmoji != null) {
      isSwitchEmoji = e.detail.isSwitchEmoji;
    }
    if (!isSwitchEmoji) {
      var reviewTextareaShow = _this.data.reviewTextareaShow;
      _this.setData({
        reviewTextareaShow: false
      })
    }
  },

  /**
   * 点评的texteare的输入事件
   */
  reviewTextareaInput: function (e) {
    var _this = this;
    var reviewTextarea = e.detail.value;
    _this.setData({
      reviewTextarea: reviewTextarea
    })
  },

  /**
   * 获取圈子信息
   */
  getCircleDetails: function () {
    var _this = this;
    var circleid = _this.data.circleid;
    var data = {};
    data.circleid = circleid;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        data.openid = openid;
        data.access_token = res.access_token;
        _this.getCircleDetailsQuery(api.Home_GetCircleDetailsApiUrl, data);
      })
    } else {
      _this.getCircleDetailsQuery(api.Home_GetCircleDetailsUrl, data);
    }
  },

  /**
   * 获取圈子信息：请求
   */
  getCircleDetailsQuery: function (url, data) {
    var _this = this;
    util.post(url, data).then(function (res) {
      if (res.code == 200) {
        var json = res.result.json;
        if (json != null) {
          _this.setData({
            albumInfo: json.albumInfo,
            mainUser: json.mainUser,
            ordContractList: json.ordContractList,
            ordInterest: json.ordInterest,
            energySize: json.energySize,
            ordInterestJoinCount: json.ordInterestJoinCount,
            collectionUserCount: json.collectionUserCount,
            collectionTotalCount: json.collectionTotalCount,
            diaryCount: json.diaryCount,
            thisInterestJoinUser: json.thisInterestJoinUser,
            mainUserSetup: json.mainUserSetup,
            title: json.ordInterest.title,
            mainBasHomeinfo: json.mainBasHomeinfo,
            maxCommission: json.maxCommission
          })

          _this.checkMainCirclePhone();

          var isClock = _this.checkClockTime();
          _this.setData({
            isClock: isClock
          })
          // 获取圈子主题信息
          _this.getThemeAndGroupByCircle();

          var ordInterest_circleNotice = json.ordInterest.circleNotice;
          var thisInterestJoinUser_circleNotice = json.thisInterestJoinUser.circleNotice;
          if (ordInterest_circleNotice != thisInterestJoinUser_circleNotice && ordInterest_circleNotice != null && ordInterest_circleNotice.length > 0 && json.thisInterestJoinUser.identitytype == 0) {
            _this.announcementTap();
          }

          // 获取成员信息
          _this.getInterestJoin();
          // 获取推荐信息
          _this.getCircleRecommendInfo();
        }
      }
    });
  },

  /**
   * 校验是否可以打卡
   */
  checkClockTime: function () {
    var _this = this;
    var clockState = 0;// 打卡状态：0初始化，1已过每日限定时间，2未开始，3已结束，100正常
    var ordInterest = _this.data.ordInterest;
    var now = new Date();
    var isClock = false;
    var projectdateIdentification = ordInterest.projectdateIdentification;
    if (projectdateIdentification == 0) {
      // 打卡时间不限
      isClock = true;
      clockState = 100;
    } else {
      var nowTime = now.getTime();
      var projectdateStart = new Date(ordInterest.projectdateStart.replace(/-/g, '/')).getTime();
      var projectdateEnd = new Date(ordInterest.projectdateEnd.replace(/-/g, '/')).getTime();
      if (nowTime >= projectdateStart && nowTime <= projectdateEnd) {
        var cardingtimesetting = ordInterest.cardingtimesetting;
        if (cardingtimesetting == 0) {
          // 打卡时间不限
          isClock = true;
          clockState = 100;
        } else {
          var cardingstarttime = new Date(ordInterest.cardingstarttime.replace(/-/g, '/')).getTime();
          var cardingendtime = new Date(ordInterest.cardingendtime.replace(/-/g, '/')).getTime();
          var nowHours = now.getHours();
          var nowMinutes = now.getMinutes();
          var nowSeconds = now.getSeconds();
          var h = [_this.formatNumber(nowHours), _this.formatNumber(nowMinutes), _this.formatNumber(nowSeconds)].join(':');
          var nowHoursTime = new Date("1970/01/01 " + h).getTime();
          if (nowHoursTime >= cardingstarttime && nowHoursTime <= cardingendtime) {
            isClock = true;
            clockState = 100;
          } else {
            // 已过每日限定时间打卡
            clockState = 1;
          }
        }
      } else if (nowTime > projectdateEnd) {
        // 已结束
        clockState = 3;
        _this.setData({
          allCententCheckedIndex: 6
        })
      } else if (nowTime < projectdateStart) {
        // 未开始
        clockState = 2;
      }
    }
    var clockData = {};
    clockData.clockState = clockState;
    if (ordInterest.projectdateStart != null && ordInterest.projectdateStart != '') {
      clockData.projectdateStart = util.formatDate(new Date(ordInterest.projectdateStart.replace(/-/g, '/')));
    }
    if (ordInterest.projectdateEnd != null && ordInterest.projectdateEnd != '') {
      clockData.projectdateEnd = util.formatDate(new Date(ordInterest.projectdateEnd.replace(/-/g, '/')));
    }
    if (ordInterest.cardingstarttime != null && ordInterest.cardingstarttime != '') {
      clockData.cardingstarttime = util.formatDate(new Date(ordInterest.cardingstarttime.replace(/-/g, '/')));
    }
    if (ordInterest.cardingendtime != null && ordInterest.cardingendtime != '') {
      clockData.cardingendtime = util.formatDate(new Date(ordInterest.cardingendtime.replace(/-/g, '/')));
    }
    _this.setData({
      clockData: clockData
    })
    if (clockData.clockState == 2) {
      _this.js_clockTime();
    }
    return isClock;
  },

  /**
   * 计算开始时间
   */
  js_clockTime: function () {
    var _this = this;
    var ordInterest = _this.data.ordInterest;
    var t1 = new Date(ordInterest.projectdateStart.replace(/-/g, '/'))
    var t2 = new Date()
    var usedTime = t1.getTime() - t2.getTime();
    var day = Math.floor(usedTime / (24 * 3600 * 1000));
    var leave1 = usedTime % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
    var hour = Math.floor(leave1 / (3600 * 1000));
    var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
    var minutes = Math.floor(leave2 / (60 * 1000));
    var leave3 = leave2 % (60 * 1000); //计算分后剩余的毫秒数
    var seconds = Math.floor(leave3 / 1000);
    if (hour < 10) {
      hour = "0" + hour.toString();
    }
    if (minutes < 10) {
      minutes = "0" + minutes.toString();
    }
    if (seconds < 10) {
      seconds = "0" + seconds.toString();
    }
    _this.setData({
      ["clockData.xcDay"]: day,
      ["clockData.xcTime"]: hour + ":" + minutes + ":" + seconds
    })
  },

  /**
   * 跳转到编辑页面
   */
  navigateToEditdetails: function () {
    var _this = this;
    var circleid = _this.data.circleid;
    wx.navigateTo({
      url: '../../editdetails/editdetails?circleid=' + circleid + "&energyInfoResults=false"
    })
  },

  formatNumber: function (n) {
    n = n.toString();
    return n[1] ? n : '0' + n
  },

  /**
   * 收藏或取消收藏
   */
  collectionTap: function (e) {
    var _this = this;
    var circleid = _this.data.circleid;
    var collectionUserCount = _this.data.collectionUserCount;
    var collectionTotalCount = _this.data.collectionTotalCount;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.circleid = circleid;
        data.access_token = res.access_token;
        util.post(api.Home_OperationCollectionCircleApiUrl, data).then(function (res) {
          if (collectionUserCount > 0) {
            _this.setData({
              collectionUserCount: 0,
              collectionTotalCount: parseInt(collectionTotalCount - 1),
              cancelCollectionShow: false,
              circleOperationShow: false
            })
          } else {
            _this.setData({
              collectionUserCount: 1,
              collectionTotalCount: parseInt(collectionTotalCount + 1),
              collectionShow: true,
              circleOperationShow: false,
            })
          }
        })
      })
    }
  },

  /**
   * 收藏成功之后的弹窗关闭
   */
  collectionShow: function () {
    var _this = this;
    _this.setData({
      collectionShow: !_this.data.collectionShow
    })
  },

  /**
   * 取消收藏时弹窗
   */
  cancelCollectionShow: function () {
    var _this = this;
    _this.setData({
      cancelCollectionShow: !_this.data.cancelCollectionShow,
      circleOperationShow: false,
    })
  },

  /**
   * 公告栏的弹出
   */
  announcementTap: function () {
    var _this = this;
    var announcementShow = _this.data.announcementShow;
    _this.setData({
      announcementShow: !announcementShow
    })
    if (announcementShow) {
      var ordInterest_circleNotice = _this.data.ordInterest.circleNotice;
      var thisInterestJoinUser_circleNotice = _this.data.thisInterestJoinUser.circleNotice;
      if (ordInterest_circleNotice != thisInterestJoinUser_circleNotice) {
        _this.updateCircleNoticeByJoin();
      }
    }
  },

  /**
   * 修改圈子参与用户的公告
   */
  updateCircleNoticeByJoin: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        data.circleid = _this.data.circleid;
        data.circleNotice = _this.data.ordInterest.circleNotice;
        util.post(api.Home_UpdateCircleNoticeByJoinApiUrl, data).then(function (res) { });
      })
    }
  },

  /**
   * 公告栏的编辑
   */
  announcementDditor: function () {
    var _this = this;
    _this.setData({
      announcementTextareaDisabled: false
    })
  },

  /**
   * 公告栏的确定
   */
  announcementCommit: function () {
    var _this = this;
    var circleNotice = _this.data.ordInterest.circleNotice;
    var announcementTextareaDisabled = _this.data.announcementTextareaDisabled;
    var openid = app.globalData.logininfo.openid;
    if (circleNotice != null && announcementTextareaDisabled == false) {
      if (openid != null && openid != "") {
        wx.showLoading({
          title: "提交中"
        })
        // 已登录
        util.post(api.fetchToken()).then(function (res) {
          if (res.access_token != '') {
            return Promise.resolve({
              access_token: res.access_token
            });
          }
        }).then(function (res) {
          var data = {};
          data.openid = openid;
          data.access_token = res.access_token;
          data.circleid = _this.data.circleid;
          data.circleNotice = circleNotice;
          util.post(api.Home_UpdateCircleNoticeApiUrl, data).then(function (res) {
            wx.hideLoading();
            if (res.code == 200) {
              _this.updateCircleNoticeByJoin();
            }
          });
        })
      } else {
        util.dialogAlert("未进行登录");
      }
    }
    _this.setData({
      announcementShow: false,
      announcementTextareaDisabled: true,
      ["ordInterest.circleNotice"]: circleNotice
    })
  },

  /**
   * 选中下标（1日记  2详情  3目录  4成员）
   */
  allCententCheckedIndexBindTap: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    if (index == 3) {
      wx.navigateTo({
        url: '../circledetails/circledetails?poTopViewIndex=1&circleid=' + _this.data.circleid,
      })
    } else if (index == 5) {
      wx.navigateTo({
        url: '../circledetails/circledetails?poTopViewIndex=0&circleid=' + _this.data.circleid,
      })
    } else {
      _this.setData({
        allCententCheckedIndex: index
      })
    }
  },

  /**
   * 播放或暂停动作：日记
   */
  voiceBoFang_diary: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var yindex = e.currentTarget.dataset.yindex;
    var diaryAudioList = _this.data.diaryInfoList[index].diaryAudioList[yindex];
    var boFangImage = diaryAudioList.boFangImage;
    var ip = diaryAudioList.ip;
    var name = diaryAudioList.name;
    var currentTime = diaryAudioList.currentTime;
    var audiourl = diaryAudioList.url;
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (boFangImage == api.AudioBoFangImage_Name) {
      // 切换至暂停状态
      wx.pauseBackgroundAudio();//暂停播放音乐
      backgroundAudioManager.pause();//暂停播放音乐
      _this.setData({
        ["diaryInfoList[" + index + "].diaryAudioList[" + yindex + "].boFangImage"]: api.AudioNoBoFangImage_Name
      });
    } else {
      // 切换至播放状态
      wx.stopBackgroundAudio();////暂停正在播放音乐
      backgroundAudioManager.startTime = currentTime;//设置音乐开始时间
      backgroundAudioManager.title = name;
      backgroundAudioManager.src = ip + audiourl;
      backgroundAudioManager.play();
      //    背景音频自然播放结束事件
      backgroundAudioManager.onEnded(function () {
        _this.setData({
          ["diaryInfoList[" + index + "].diaryAudioList[" + yindex + "].startDate"]: "00:00",
          ["diaryInfoList[" + index + "].diaryAudioList[" + yindex + "].currentTime"]: 0,
          ["diaryInfoList[" + index + "].diaryAudioList[" + yindex + "].boFangImage"]: api.AudioNoBoFangImage_Name
        });
      })
      //背景音频播放进度更新事件
      backgroundAudioManager.onTimeUpdate(function (callback) {
        var position = parseInt(backgroundAudioManager.currentTime);
        var startDate = util.digitalFormatTime(position);
        _this.setData({
          ["diaryInfoList[" + index + "].diaryAudioList[" + yindex + "].currentTime"]: backgroundAudioManager.currentTime,
          ["diaryInfoList[" + index + "].diaryAudioList[" + yindex + "].startDate"]: startDate
        });
      })
      _this.setData({
        ["diaryInfoList[" + index + "].diaryAudioList[" + yindex + "].boFangImage"]: api.AudioBoFangImage_Name
      });
    }
  },

  /**
   * 播放音乐（滚动条事件）：日记
   */
  voiceSlider_diary: function (e) {
    var _this = this;
    var position = e.detail.value;
    var index = e.currentTarget.dataset.index;
    var yindex = e.currentTarget.dataset.yindex;
    var diaryAudioList = _this.data.diaryInfoList[index].diaryAudioList[yindex];
    var boFangImage = diaryAudioList.boFangImage;
    var startDate = util.digitalFormatTime(position);
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (boFangImage == api.AudioBoFangImage_Name) {
      //正在播放状态：不知道为什么，录音的在调用backgroundAudioManager.seek(Math.floor(position))方法无效，所以改成一下这种方式
      _this.setData({
        ["diaryInfoList[" + index + "].diaryAudioList[" + yindex + "].currentTime"]: position,
        ["diaryInfoList[" + index + "].diaryAudioList[" + yindex + "].boFangImage"]: api.AudioNoBoFangImage_Name
      });
      _this.voiceBoFang_diary(e);
    } else {
      // 未播放状态
      _this.setData({
        ["diaryInfoList[" + index + "].diaryAudioList[" + yindex + "].currentTime"]: position,
        ["diaryInfoList[" + index + "].diaryAudioList[" + yindex + "].startDate"]: startDate
      });
    }
  },

  /**
   * 公告栏的texteare输入事件
   */
  circleNoticeInput: function (e) {
    var _this = this;
    var circleNotice = e.detail.value;
    _this.setData({
      ["ordInterest.circleNotice"]: circleNotice
    })
  },

  /**
   * 获取日记详情
   */
  getDiaryInfo: function () {
    var _this = this;
    var circleid = _this.data.circleid;
    var diaryInfoPageNum = _this.data.diaryInfoPageNum;
    var diaryInfoPageSize = _this.data.diaryInfoPageSize;
    var screeningData = _this.data.screeningData;
    var openid = app.globalData.logininfo.openid;
    var data = {};
    data.circleid = circleid;
    data.pageNum = diaryInfoPageNum;
    data.pageSize = diaryInfoPageSize;
    data.screeningData = JSON.stringify(screeningData);
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        data.openid = openid;
        data.access_token = res.access_token;
        _this.getDiaryInfoQuery(api.Home_GetDiaryInfoApiUrl, data);
      })
    } else {
      _this.getDiaryInfoQuery(api.Home_GetDiaryInfoUrl, data);
    }
  },

  /**
   * 获取日记详情：请求
   */
  getDiaryInfoQuery: function (url, data) {
    var _this = this;
    util.post(url, data).then(function (res) {
      if (res.code == 200) {
        var diaryInfoTotalPages = res.result.pages;
        var resultList = res.result.list;
        var list = _this.data.diaryInfoList;
        for (var i = 0; i < resultList.length; i++) {
          list.push(resultList[i]);
        }
        _this.setData({
          diaryInfoList: list,
          diaryInfoTotalPages: diaryInfoTotalPages
        })
        _this.calculateHeight();

        // 控制打卡完成后页面自动滚动到打卡信息
        var jumpDiary = _this.data.jumpDiary;
        var allCententCheckedIndex = _this.data.allCententCheckedIndex;
        if (jumpDiary && allCententCheckedIndex == 1) {
          var query = wx.createSelectorQuery();
          query.select('.thirdHeight').boundingClientRect(function (rect) {
            var height = rect.height;
            wx.pageScrollTo({
              scrollTop: height,
              duration: 300
            })
            _this.setData({
              jumpDiary: false
            })
          }).exec();
        }
      }
    });
  },

  /**
   * 圈主首次进入圈子弹窗的下一步：第一步
   */
  firstSteplayer: function () {
    var _this = this;
    _this.setData({
      firstSteplayerShow: false,
      secondSteplayerShow: true,
      maskLayerShow: true
    })
  },

  /**
   * 圈主首次进入圈子弹窗的下一步：第二步
   */
  secondSteplayer: function () {
    var _this = this;
    _this.setData({
      secondSteplayerShow: false,
      thirdSteplayerShow: true,
      setShow: true,
      maskLayerShow: true
    })
  },

  /**
   * 圈主首次进入圈子弹窗的下一步：第三步
   */
  thirdSteplayer: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    _this.setData({
      thirdSteplayerShow: false,
      maskLayerShow: false
    })
    util.post(api.fetchToken()).then(function (res) {
      if (res.access_token != '') {
        return Promise.resolve({
          access_token: res.access_token
        });
      }
    }).then(function (res) {
      var data = {};
      data.openid = openid;
      data.access_token = res.access_token;
      data.circleOneCreate = "1";
      util.post(api.Home_UpdateUserSetupApiUrl, data).then(function (res) {
        if (res.code == 200) {
        }
      })
    })
  },

  /**
   * 点评弹窗
   */
  commentsShow: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      reviewBottomIndex: index,
      review_diary: _this.data.diaryInfoList[index],
      reviewBottomShow: false,
      reviewDialogShow: true
    })
  },

  /**
   * 点评的星星点击事件
   */
  reviewScoreTap: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var imageList = _this.data.reviewImageList.imageList;
    var clickNumber = imageList[index].clickNumber;
    for (var i = 0; i < imageList.length; i++) {
      imageList[i].clickNumber = 0;
    }
    for (var i = 0; i < index; i++) {
      imageList[i].clickNumber = 2;
    }
    if (clickNumber < 2) {
      imageList[index].clickNumber = clickNumber + 1;
    } else {
      imageList[index].clickNumber = 0;
    }
    var totalClickNumber = 0;
    for (var i = 0; i < imageList.length; i++) {
      totalClickNumber = totalClickNumber + imageList[i].clickNumber;
    }
    var reviewImageList = { "imageList": imageList, "totalScore": totalClickNumber };
    _this.setData({
      reviewImageList: reviewImageList
    })
  },

  /**
   * 点评录音
   */
  reviewAudioTap: function () {
    var _this = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.record']) {
          // 未授权
          wx.authorize({
            scope: 'scope.record',
            success() {
              _this.reviewAudioStart();
            },
            fail: function () {
              // 拒绝授权
              _this.setData({
                audioOauhRefusedDialogShow: true
              })
            }
          })
        } else {
          // 已授权
          _this.reviewAudioStart();
        }
      }
    })
  },

  /**
   * 开始录音：点评
   */
  reviewAudioStart: function () {
    var _this = this;
    var reviewAudio = {};
    reviewAudio.isupload = true;
    reviewAudio.state = "1";// 1正在录音  2录音完毕（state==2的时候，playState无效）
    reviewAudio.playState = "1";// 1正常录音  2暂停录音
    reviewAudio.isBoFang = "0";
    reviewAudio.totalTime = 0;
    reviewAudio.totalDate = "00:00";
    reviewAudio.isVoiceDialogShow = true;
    _this.setData({
      reviewAudio: reviewAudio
    })

    const recorderOptions = {
      duration: util.getAudioFileMaxTime("diaryReview"),//指定录音的时长，单位 ms，默认十分钟
      format: 'mp3'
    }
    //开始录音
    recorderManager.start(recorderOptions);

    // 定时器计算录音时间
    _this.doReviewRecordInterval();

    // 录音结束
    recorderManager.onStop((res) => {
      _this.reviewStopRecorderExecute(res);
    });

    // 录音中断
    recorderManager.onInterruptionBegin((res) => {
      recorderManager.stop();
      _this.reviewStopRecorderExecute(res);
    });
  },

  /**
   * 播放或暂停动作
   */
  reviewAudioBoFang: function (e) {
    var _this = this;
    var src = _this.data.reviewAudio.src;
    var title = _this.data.reviewAudio.title;
    var currentTime = _this.data.reviewAudio.currenttime;
    var isBoFang = _this.data.reviewAudio.isBoFang;
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (isBoFang == "1") {
      // 切换至暂停状态
      backgroundAudioManager.pause();//暂停播放音乐
      _this.setData({
        ["reviewAudio.isBoFang"]: "0"
      });
    } else {
      // 切换至播放状态
      wx.stopBackgroundAudio();//暂停正在播放音乐
      backgroundAudioManager.startTime = currentTime;//设置音乐开始时间
      backgroundAudioManager.title = title;
      backgroundAudioManager.src = src;
      backgroundAudioManager.play();
      //    背景音频自然播放结束事件
      backgroundAudioManager.onEnded(function () {
        _this.setData({
          ["reviewAudio.currentTime"]: 0,
          ["reviewAudio.isBoFang"]: "0",
          ["reviewAudio.startDate"]: "00:00"
        });
      })
      //背景音频播放进度更新事件
      backgroundAudioManager.onTimeUpdate(function (callback) {
        var position = Math.round(backgroundAudioManager.currentTime);
        var voiceStartDate = util.digitalFormatTime(position);
        _this.setData({
          ["reviewAudio.currentTime"]: backgroundAudioManager.currentTime,
          ["reviewAudio.startDate"]: voiceStartDate
        });
      })

      _this.setData({
        ["reviewAudio.isBoFang"]: "1"
      });
    }
  },

  /**
   * 清除定时器
   */
  doClearInterval: function () {
    clearInterval(recordInterval);
    recordInterval = null;
  },

  /**
   * 定时器计算录音时间
   */
  doReviewRecordInterval: function () {
    var _this = this;
    if (recordInterval == null) {
      recordInterval = setInterval(function () {
        var reviewAudio = _this.data.reviewAudio;
        var totalTime = reviewAudio.totalTime + 1;
        var totalDate = util.digitalFormatTime(totalTime);
        _this.setData({
          ["reviewAudio.totalTime"]: totalTime,
          ["reviewAudio.totalDate"]: totalDate
        });
      }, 1000);
    }
  },

  /**
   * 停止录音后的业务代码：点评
   */
  reviewStopRecorderExecute: function (tempFile) {
    var _this = this;
    _this.doClearInterval();
    var isVoiceDialogShow = _this.data.reviewAudio.isVoiceDialogShow;
    if (isVoiceDialogShow) {
      var totalTime = parseInt(tempFile.duration / 1000);
      var reviewAudio = _this.data.reviewAudio;
      reviewAudio.state = "2";
      reviewAudio.src = tempFile.tempFilePath;
      reviewAudio.title = "录音音频";
      reviewAudio.currentTime = 0;
      reviewAudio.totalTime = totalTime;
      reviewAudio.fileSize = tempFile.fileSize;
      reviewAudio.startDate = "00:00";
      reviewAudio.totalDate = util.digitalFormatTime(totalTime);
      reviewAudio.isBoFang = "0";
      _this.setData({
        reviewAudio: reviewAudio
      })
    }
  },

  /**
   * 暂停录音：点评
   */
  reviewPauseRecorder: function (e) {
    var _this = this;
    _this.setData({
      ["reviewAudio.playState"]: "2"
    });
    recorderManager.pause();
    _this.doClearInterval();
  },

  /**
   * 继续录音：点评
   */
  reviewResumeRecorder: function (e) {
    var _this = this;
    _this.setData({
      ["reviewAudio.playState"]: "1"
    })
    recorderManager.resume();
    _this.doReviewRecordInterval();
  },

  /**
   * 停止录音：点评
   */
  reviewStopRecorder: function (e) {
    var _this = this;
    recorderManager.stop();
    recorderManager.onStop((res) => {
      _this.reviewStopRecorderExecute(res);
    });
  },

  /**
   * 清空录音：点评
   */
  clearReviewRecorder: function () {
    var _this = this;
    _this.setData({
      ["reviewAudio.isVoiceDialogShow"]: false
    })
    _this.doClearInterval();
    recorderManager.stop();

    setTimeout(function () {
      _this.reviewAudioTap();
    }, 100)
  },

  /**
   * 删除录音：点评
   */
  deleteReviewRecorder: function () {
    var _this = this;
    _this.doClearInterval();
    recorderManager.stop();
    var isupload = _this.data.reviewAudio.isupload;
    var reviewAudio = {};
    reviewAudio.isupload = isupload;
    if (!isupload) {
      // 删除的是已存数据库的
      reviewAudio.isDelete = true;
    }
    _this.setData({
      reviewAudio: reviewAudio
    })
  },

  /**
   * 点评图片
   */
  reviewImageTap: function () {
    var _this = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        var reviewImage = {};
        reviewImage = res.tempFiles[0];
        reviewImage.isupload = true;
        _this.setData({
          reviewImage: reviewImage
        })
      }
    })
  },

  /**
   * 删除点评图片
   */
  deleteReviewImage: function () {
    var _this = this;
    var isupload = _this.data.reviewImage.isupload;
    var reviewImage = {};
    reviewImage.isupload = isupload;
    if (!isupload) {
      // 删除的是已存数据库的
      reviewImage.isDelete = true;
    }
    _this.setData({
      reviewImage: reviewImage
    })
  },

  /**
   * 校验第一个主题是否可以打卡
   */
  checkUserThemeClock: function (source) {
    var _this = this;
    var circleid = _this.data.circleid;
    var themeInfo = _this.data.themeInfo;
    var themeid = "";
    if (themeInfo.themeGroup != null) {
      themeid = themeInfo.themeGroup.id;
    } else if (themeInfo.theme != null) {
      themeid = themeInfo.theme.id;
    }
    if (null != themeid && String(themeid).length > 0) {
      // 需要校验当前主题是否可以打卡
      var themeContentType = themeInfo.contentType;
      var openid = app.globalData.logininfo.openid;
      if (openid != null && openid != "") {
        // 已登录
        util.post(api.fetchToken()).then(function (res) {
          if (res.access_token != '') {
            return Promise.resolve({
              access_token: res.access_token
            });
          }
        }).then(function (res) {
          var data = {};
          data.openid = openid;
          data.circleid = circleid;
          data.themeid = themeid;
          data.access_token = res.access_token;
          util.post(api.Interest_CheckUserThemeClockApi, data).then(function (res) {
            if (res.code == 200) {
              var result = res.result;
              var type = result.type;
              var message = result.message;
              if (source == 1) {
                // 跳转
                if (type == 1) {
                  //可以进行打卡 
                  wx.navigateTo({
                    url: '../circleinteraction/noThemeClock/noThemeClock?themeid=' + themeid + '&circleid=' + circleid,
                  })
                } else if (type == 2) {
                  //不可以进行打卡
                  util.showToast(message, "none");
                } else if (type == 4) {
                  //需要先进行回答主题
                  if (themeContentType == 4 || themeContentType == 5) {
                    // 宝贝
                    wx.navigateTo({
                      url: '../../../../../../interest/pages/interest/theme/goodsDetails/goodsDetails?preview=0&themeid=' + themeid,
                    })
                  } else if (themeContentType == 1) {
                    // 知识分享
                    wx.navigateTo({
                      url: '../../../../../../interest/pages/interest/theme/themeDetails/themeResult/themeResult?themeid=' + themeid,
                    })
                  } else {
                    wx.navigateTo({
                      url: '../../../../../../interest/pages/interest/theme/themeDetails/themeDetails?preview=0&themeid=' + themeid,
                    })
                  }
                }
              } else if (source == 2) {
                if (type == 2) {
                  // 不可以打卡
                  var isClock = _this.data.isClock;
                  if (isClock) {
                    _this.setData({
                      isClock: false
                    })
                  }
                }
              }
            } else {
              util.showToast(res.message, "none");
            }
          })
        })
      }
    } else {
      if (source == 1) {
        wx.navigateTo({
          url: '../circleinteraction/noThemeClock/noThemeClock?themeid=&circleid=' + circleid,
        })
      }
    }
  },

  /**
   * 打卡动作
   */
  doClock: function () {
    var _this = this;
    _this.checkUserThemeClock(1);
  },

  /**
   * 添加快捷语弹窗的显示
   */
  quickLanguageShow: function () {
    var _this = this;
    var quickLanguageShow = _this.data.quickLanguageShow;
    _this.setData({
      quickLanguageShow: true
    })
  },

  /**
   * 添加快捷语弹窗的显示：编辑
   */
  quickLanguageShow2: function () {
    var _this = this;
    var quickLanguageShow = _this.data.quickLanguageShow;
    var index = _this.data.selectReviewQuickIndex;
    var ordReviewQuickId = _this.data.reviewQuickList[index].id;
    var ordReviewQuickText = _this.data.reviewQuickList[index].text;
    _this.setData({
      quickLanguageBottomShow: false,
      quickLanguageShow: true,
      ordReviewQuickText: ordReviewQuickText,
      ordReviewQuickTextLength: ordReviewQuickText.length,
      ordReviewQuickId: ordReviewQuickId,
      selectReviewQuickIndex: ''
    })
  },

  /**
  * 添加快捷语弹窗的隐藏
  */
  quickLanguageBottomClose: function () {
    var _this = this;
    _this.setData({
      quickLanguageBottomShow: false,
      selectReviewQuickIndex: '',
      ordReviewQuickId: ''
    })
  },

  /**
   * 快捷语置顶
   */
  quickLanguagePlacedTop: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    var index = _this.data.selectReviewQuickIndex;
    var ordReviewQuickId = _this.data.reviewQuickList[index].id;
    var isPlacedtop = _this.data.reviewQuickList[index].isPlacedtop;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.ordReviewQuickId = ordReviewQuickId;
        data.isPlacedtop = isPlacedtop == 0 ? "1" : "0";
        data.access_token = res.access_token;
        util.post(api.Home_SaveOrUpdateReviewQuickApiUrl, data).then(function (res) {
          _this.getOrdReviewQuick();
          _this.quickLanguageBottomClose();
        })
      })
    }
  },

  /**
   * 删除快捷语
   */
  deleteOrdReviewQuick: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    var index = _this.data.selectReviewQuickIndex;
    var ordReviewQuickId = _this.data.reviewQuickList[index].id;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.ordReviewQuickId = ordReviewQuickId;
        data.access_token = res.access_token;
        util.post(api.Home_DeleteOrdReviewQuickApiUrl, data).then(function (res) {
          if (res.code == 200) {
            _this.setData({
              quickLanguageBottomShow: false,
              selectReviewQuickIndex: ''
            })
            _this.getOrdReviewQuick();
          }
        })
      })
    }
  },

  /**
   * 添加快捷语弹窗的关闭
   */
  quickLanguageClose: function () {
    var _this = this;
    var quickLanguageShow = _this.data.quickLanguageShow;
    _this.setData({
      quickLanguageShow: false,
      ordReviewQuickText: '',
      ordReviewQuickId: '',
      selectReviewQuickIndex: '',
      ordReviewQuickTextLength: 0
    })
  },

  /**
   * 获取快捷语信息
   */
  getOrdReviewQuick: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        util.post(api.Home_GetOrdReviewQuickApiUrl, data).then(function (res) {
          if (res.code == 200) {
            var reviewQuickList = res.result.list;
            _this.setData({
              reviewQuickList: reviewQuickList
            })
          }
        })
      })
    }
  },

  /**
   * 快捷语的list右侧的点点点选中事件
   */
  selectReviewQuick: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      selectReviewQuickIndex: index,
      quickLanguageBottomShow: true
    })
  },

  /**
   * 快捷语的textarea输入事件
   */
  ordReviewQuickTextInput: function (e) {
    var _this = this;
    var value = e.detail.value;
    _this.setData({
      ordReviewQuickText: value,
      ordReviewQuickTextLength: value.length
    })
  },

  /**
   * 预览图片：正在编辑的点评图片
   */
  previewSaveReviewImage: function (e) {
    var _this = this;
    var reviewImage = _this.data.reviewImage;
    wx.previewImage({
      current: reviewImage.path, // 当前显示图片的http链接
      urls: [reviewImage.path] // 需要预览的图片http链接列表
    })
  },

  /**
   * 保存或者删除评语
   */
  saveOrUpdateReviewQuick: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    var ordReviewQuickId = _this.data.ordReviewQuickId;
    var ordReviewQuickText = _this.data.ordReviewQuickText;
    if (openid != null && openid != "" && ordReviewQuickText.length > 0) {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.ordReviewQuickId = ordReviewQuickId;
        data.ordReviewQuickText = ordReviewQuickText;
        data.access_token = res.access_token;
        util.post(api.Home_SaveOrUpdateReviewQuickApiUrl, data).then(function (res) {
          _this.getOrdReviewQuick();
          _this.quickLanguageClose();
        })
      })
    }
  },

  /**
   * 快捷评语选中事件
   */
  reviewQuickCenterTap: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var text = _this.data.reviewQuickList[index].text;
    var reviewTextarea = _this.data.reviewTextarea;
    if (reviewTextarea.length > 0) {
      text = reviewTextarea + "，" + text;
    }
    _this.setData({
      reviewTextarea: text
    })
  },

  /**
   * 取消点评
   */
  closeReview: function () {
    var _this = this;
    _this.deleteCommentsRecorder();
    _this.setData({
      review_diary: {},
      reviewDialogShow: false,
      reviewImageList: { "imageList": [{ "clickNumber": 0 }, { "clickNumber": 0 }, { "clickNumber": 0 }, { "clickNumber": 0 }, { "clickNumber": 0 }], "totalScore": 0 },
      reviewTextarea: '',
      reviewAudio: {},
      reviewImage: {},
      reviewBottomIndex: '',
      reviewBottomYIndex: '',
      ordReviewId: ''
    })
  },

  /**
   * 发表点评
   */
  submitReview: function () {
    var _this = this;
    var totalScore = _this.data.reviewImageList.totalScore;
    var reviewTextarea = _this.data.reviewTextarea;
    var reviewAudio = _this.data.reviewAudio;
    var reviewImage = _this.data.reviewImage;
    if (!(reviewTextarea.length > 0 || (reviewAudio.state != null && reviewAudio.state.length > 0) || (reviewImage.path != null && reviewImage.path.length > 0))) {
      util.dialogAlert("评论内容不能为空");
      return false;
    } else if (reviewAudio.state != null && reviewAudio.state == "1") {
      util.dialogAlert("正在录制音频中");
      return false;
    }
    wx.showLoading({
      title: '保存中',
    })
    _this.setData({
      isSubmitAll: false
    })
    var uploadInfoList = [];
    if (reviewImage.path != null && reviewImage.path.length > 0 && reviewImage.isupload) {
      var uploadInfo = {};
      uploadInfo.type = "1";// 类型:1图片  2音频  3视频
      uploadInfo.filePath = reviewImage.path;
      uploadInfoList.push(uploadInfo);
    }
    if (reviewAudio.state != null && reviewAudio.state == "2" && reviewAudio.isupload) {
      var uploadInfo = {};
      uploadInfo.type = "2";// 类型:1图片  2音频  3视频
      uploadInfo.filePath = reviewAudio.src;
      uploadInfoList.push(uploadInfo);
    }
    if (uploadInfoList.length > 0) {
      // 开始请求:要先上传
      _this.uploadFileQuery(uploadInfoList, 0);
    } else {
      _this.saveReview();
    }
  },

  /**
   * 上传
   */
  uploadFileQuery: function (data, queryIndex) {
    var _this = this;
    var queryData = data[queryIndex];
    var queryUrl = "";
    switch (queryData.type) {
      case "1":
        // 图片
        queryUrl = api.File_doImageUpload;
        break;
      case "2":
        // 音频
        queryUrl = api.File_doAudioUpload;
        break;
    }
    wx.uploadFile({
      url: queryUrl,
      filePath: queryData.filePath,
      name: 'file',
      formData: {
        "type": "4"
      },
      success(res) {
        var data = JSON.parse(res.data);
        if (data.code == 200) {
          var ip = data.result.ip;
          var path = data.result.path;
          switch (queryData.type) {
            case "1":
              // 图片
              _this.setData({
                ["reviewImage.ip"]: ip,
                ["reviewImage.path"]: path
              })
              break;
            case "2":
              // 音频
              _this.setData({
                ["reviewAudio.ip"]: ip,
                ["reviewAudio.src"]: path
              })
              break;
          }
        }
      },
      fail(res) {
        // 失败
      },
      complete(res) {
        // 结束：
        if (queryIndex < data.length - 1) {
          // 图片未上传完成，继续上传
          queryIndex++;
          _this.uploadFileQuery(data, queryIndex);
        } else {
          // 上传完成，执行save请求
          _this.saveReview();
        }
      }
    })
  },

  /**
   * save点评请求
   */
  saveReview: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    util.post(api.fetchToken()).then(function (res) {
      if (res.access_token != '') {
        return Promise.resolve({
          access_token: res.access_token
        });
      }
    }).then(function (res) {
      var data = {};
      data.openid = openid;
      data.access_token = res.access_token;
      data.circleid = _this.data.circleid;
      data.ordDiaryid = _this.data.review_diary.ordDiary.id;
      data.ordReviewScore = _this.data.reviewImageList.totalScore;
      data.ordReviewText = _this.data.reviewTextarea;
      data.ordReviewId = _this.data.ordReviewId;
      if (_this.data.reviewAudio.isupload || _this.data.reviewAudio.isDelete) {
        data.ordReviewAudio = JSON.stringify(_this.data.reviewAudio);
      } else {
        data.ordReviewAudio = "";
      }
      if (_this.data.reviewImage.isupload || _this.data.reviewImage.isDelete) {
        data.ordReviewImage = JSON.stringify(_this.data.reviewImage);
      } else {
        data.ordReviewImage = "";
      }
      util.post(api.Home_SaveOrUpdateOrdReviewApiUrl, data).then(function (res) {
        wx.hideLoading();
        _this.setData({
          isSubmitAll: false
        })
        if (res.code == 200) {
          _this.getDiaryInfoByDiaryId(_this.data.reviewBottomIndex);
          _this.closeReview();
          var energyInfoResults = res.result.energyInfoResults;
          if (energyInfoResults == true) {
            _this.setData({
              diary_review_dialog: true
            })
            setTimeout(() => {
              _this.setData({
                diary_review_dialog: false
              })
            }, 2000);
          }
        }
      })
    })
  },

  /**
   * 播放录音：点评详情
   */
  ordReviewBoFang: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var yindex = e.currentTarget.dataset.yindex;
    var xindex = e.currentTarget.dataset.xindex;
    var ordReviewAudio = _this.data.diaryInfoList[index].ordReviewList[yindex].ordReviewAudioList[xindex];
    var isBoFang = ordReviewAudio.isBoFang;
    var ip = ordReviewAudio.ip;
    var name = ordReviewAudio.name;
    var currentTime = ordReviewAudio.currentTime;
    var audiourl = ordReviewAudio.url;
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (isBoFang == "1") {
      // 切换至暂停状态
      wx.pauseBackgroundAudio();//暂停播放音乐
      backgroundAudioManager.pause();//暂停播放音乐
      _this.setData({
        ["diaryInfoList[" + index + "].ordReviewList[" + yindex + "].ordReviewAudioList[" + xindex + "].isBoFang"]: 0
      });
    } else {
      // 切换至播放状态
      wx.stopBackgroundAudio();//暂停正在播放音乐
      backgroundAudioManager.startTime = currentTime;//设置音乐开始时间
      backgroundAudioManager.title = name;
      backgroundAudioManager.src = ip + audiourl;
      backgroundAudioManager.play();
      //    背景音频自然播放结束事件
      backgroundAudioManager.onEnded(function () {
        _this.setData({
          ["diaryInfoList[" + index + "].ordReviewList[" + yindex + "].ordReviewAudioList[" + xindex + "].currentTime"]: 0,
          ["diaryInfoList[" + index + "].ordReviewList[" + yindex + "].ordReviewAudioList[" + xindex + "].isBoFang"]: 0
        });
      })
      //背景音频播放进度更新事件
      backgroundAudioManager.onTimeUpdate(function (callback) {
        var position = parseInt(backgroundAudioManager.currentTime);
        var startDate = util.digitalFormatTime(position);
        _this.setData({
          ["diaryInfoList[" + index + "].ordReviewList[" + yindex + "].ordReviewAudioList[" + xindex + "].currentTime"]: backgroundAudioManager.currentTime,
          ["diaryInfoList[" + index + "].ordReviewList[" + yindex + "].ordReviewAudioList[" + xindex + "].startDate"]: startDate
        });
      })
      _this.setData({
        ["diaryInfoList[" + index + "].ordReviewList[" + yindex + "].ordReviewAudioList[" + xindex + "].isBoFang"]: 1
      });
    }
  },

  /**
   * 点评底部的的弹出显示
   */
  reviewBottomShow: function (e) {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    var index = e.currentTarget.dataset.index;
    var yindex = e.currentTarget.dataset.yindex;
    var ordReviewOpenid = _this.data.diaryInfoList[index].ordReviewList[yindex].ordReview.openid;
    var thisInterestJoinUser = _this.data.thisInterestJoinUser;
    var reviewBottomEditorAndDeleteIsShow = false;
    if (thisInterestJoinUser.identitytype == 1 || thisInterestJoinUser.identitytype == 2 || thisInterestJoinUser.identitytype == 3) {
      reviewBottomEditorAndDeleteIsShow = true;
    }
    if (ordReviewOpenid == openid) {
      reviewBottomEditorAndDeleteIsShow = true;
    }
    _this.setData({
      reviewBottomShow: true,
      reviewBottomIndex: index,
      reviewBottomYIndex: yindex,
      reviewBottomEditorAndDeleteIsShow: reviewBottomEditorAndDeleteIsShow
    })
  },

  /**
   * 点评底部的的弹出关闭
   */
  reviewBottomClose: function (e) {
    var _this = this;
    _this.setData({
      reviewBottomShow: false,
      reviewBottomIndex: '',
      reviewBottomYIndex: '',
      reviewBottomEditorAndDeleteIsShow: false
    })
  },

  /**
   * 编辑新点评
   */
  reviewBottomEditor: function (e) {
    var _this = this;
    var imageList = _this.data.reviewImageList.imageList;
    var index = _this.data.reviewBottomIndex;
    var yindex = _this.data.reviewBottomYIndex;
    var review_diary = _this.data.diaryInfoList[index];
    var reviewBottomInfo = review_diary.ordReviewList[yindex];
    var ordReview = reviewBottomInfo.ordReview;
    var ordReviewAudioList = reviewBottomInfo.ordReviewAudioList;
    var ordReviewImageList = reviewBottomInfo.ordReviewImageList;
    var score = ordReview.score;
    var ordReviewId = ordReview.id;
    var reviewTextarea = ordReview.text;
    var scoreIndex = 0;
    var dyScore = 0;
    if (score > 0) {
      if (score % 2 == 0) {
        scoreIndex = score / 2;
      } else {
        dyScore = 1;
        scoreIndex = (score - 1) / 2;
      }
    }
    for (var i = 0; i < imageList.length; i++) {
      imageList[i].clickNumber = 0;
    }
    for (var i = 0; i < scoreIndex; i++) {
      imageList[i].clickNumber = 2;
    }
    if (dyScore > 0) {
      imageList[scoreIndex].clickNumber = 1;
    }
    var reviewImageList = { "imageList": imageList, "totalScore": score };
    var reviewAudio = {};
    var reviewImage = {};
    if (ordReviewAudioList.length > 0) {
      var ordReviewAudio = ordReviewAudioList[0];
      reviewAudio.currentTime = 0;
      reviewAudio.isBoFang = 0;
      reviewAudio.isVoiceDialogShow = true;
      reviewAudio.isupload = false;
      reviewAudio.playState = "1";
      reviewAudio.src = ordReviewAudio.ip + ordReviewAudio.url;
      reviewAudio.startDate = "00:00";
      reviewAudio.state = "2";
      reviewAudio.title = ordReviewAudio.name;
      reviewAudio.totalDate = ordReviewAudio.totalDate;
      reviewAudio.totalTime = ordReviewAudio.totalTime;
    }
    if (ordReviewImageList.length > 0) {
      var ordReviewImage = ordReviewImageList[0];
      reviewImage.path = ordReviewImage.ip + ordReviewImage.url;
      reviewImage.isupload = false;
    }
    _this.setData({
      reviewImageList: reviewImageList,
      review_diary: review_diary,
      reviewBottomShow: false,
      reviewDialogShow: true,
      reviewTextarea: reviewTextarea,
      reviewAudio: reviewAudio,
      reviewImage: reviewImage,
      ordReviewId: ordReviewId
    })
  },

  /**
   * 删除点评弹窗
   */
  reviewBottomDelete: function () {
    var _this = this;
    _this.setData({
      reviewBottomShow: false,
      reviewBottomDeleteShow: true
    })
  },

  /**
   * 删除点评取消
   */
  reviewBottomDeleteClose: function () {
    var _this = this;
    _this.setData({
      reviewBottomIndex: '',
      reviewBottomYIndex: '',
      reviewBottomDeleteShow: false
    })
  },

  /**
   * 删除点评确定
   */
  reviewBottomDeleteSuccess: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var index = _this.data.reviewBottomIndex;
        var yindex = _this.data.reviewBottomYIndex;
        var review_diary = _this.data.diaryInfoList[index];
        var ordDiaryid = review_diary.ordReviewList[yindex].ordReview.diaryId;
        var ordReviewId = review_diary.ordReviewList[yindex].ordReview.id;
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        data.circleid = _this.data.circleid;
        data.ordDiaryid = ordDiaryid;
        data.ordReviewId = ordReviewId;
        util.post(api.Home_DeleteOrdReviewApiUrl, data).then(function (res) {
          if (res.code == 200) {
            _this.setData({
              reviewBottomIndex: '',
              reviewBottomDeleteShow: false
            })
            _this.getDiaryInfoByDiaryId(index);
          }
        })
      })
    }
  },

  /**
   * 添加或删除日记能量点赞
   */
  saveOrDeleteOrdDiaryGivelike: function (e) {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    var index = e.currentTarget.dataset.index;
    var diaryGivelikeid = e.currentTarget.dataset.givelikeid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        data.circleid = _this.data.circleid;
        data.diaryid = _this.data.diaryInfoList[index].ordDiary.id;
        data.diaryGivelikeid = diaryGivelikeid;
        util.post(api.Home_SaveOrDeleteOrdDiaryGivelikeApiUrl, data).then(function (res) {
          if (res.code == 200) {
            _this.getDiaryInfoByDiaryId(index);
            var energyInfoResults = res.result.energyInfoResults;
            if (energyInfoResults == true) {
              _this.setData({
                diary_givelike_dialog: true
              })
              setTimeout(() => {
                _this.setData({
                  diary_givelike_dialog: false
                })
              }, 2000);
            }
          }
        })
      })
    }
  },

  /**
   * 评论的弹窗打开
   */
  commentsDialogShow: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      commentsDialogShow: true,
      saveCommentsIndex: index,
      commonsBottomShow: false
    })
  },

  /**
   * 评论的弹窗关闭
   */
  commentsDialogClose: function () {
    var _this = this;
    _this.deleteCommentsRecorder();
    _this.setData({
      commentsTextarea: '',
      commentsAudio: {},
      commentsDialogShow: false,
      saveCommentsIndex: '',
      replyCommentsid: 0,
      mainReplyCommentsid: 0,
      replyCommentNickname: ''
    })
  },

  /**
   * 评论的texteare的输入事件
   */
  commentsTextareaInput: function (e) {
    var _this = this;
    var commentsTextarea = e.detail.value;
    _this.setData({
      commentsTextarea: commentsTextarea
    })
  },

  /**
  * 评论录音
  */
  commentsAudioTap: function () {
    var _this = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.record']) {
          // 未授权
          wx.authorize({
            scope: 'scope.record',
            success() {
              _this.commentsAudioStart();
            },
            fail: function () {
              // 拒绝授权
              _this.setData({
                audioOauhRefusedDialogShow: true
              })
            }
          })
        } else {
          // 已授权
          _this.commentsAudioStart();
        }
      }
    })
  },

  /**
   * 开始录音：评论
   */
  commentsAudioStart: function () {
    var _this = this;
    var commentsAudio = {};
    commentsAudio.isupload = true;
    commentsAudio.state = "1";// 1正在录音  2录音完毕（state==2的时候，playState无效）
    commentsAudio.playState = "1";// 1正常录音  2暂停录音
    commentsAudio.isBoFang = "0";
    commentsAudio.totalTime = 0;
    commentsAudio.totalDate = "00:00";
    commentsAudio.isVoiceDialogShow = true;
    _this.setData({
      commentsAudio: commentsAudio
    })

    const recorderOptions = {
      duration: util.getAudioFileMaxTime("diaryComments"),//指定录音的时长，单位 ms，默认十分钟
      format: 'mp3'
    }
    //开始录音
    recorderManager.start(recorderOptions);

    // 定时器计算录音时间
    _this.doCommentsRecordInterval();

    // 录音结束
    recorderManager.onStop((res) => {
      _this.commentsStopRecorderExecute(res);
    });

    // 录音中断
    recorderManager.onInterruptionBegin((res) => {
      recorderManager.stop();
      _this.commentsStopRecorderExecute(res);
    });
  },

  /**
   * 停止录音后的业务代码：评论
   */
  commentsStopRecorderExecute: function (tempFile) {
    var _this = this;
    _this.doClearInterval();
    var isVoiceDialogShow = _this.data.commentsAudio.isVoiceDialogShow;
    if (isVoiceDialogShow) {
      var totalTime = parseInt(tempFile.duration / 1000);
      var commentsAudio = _this.data.commentsAudio;
      commentsAudio.state = "2";
      commentsAudio.src = tempFile.tempFilePath;
      commentsAudio.title = "录音音频";
      commentsAudio.currentTime = 0;
      commentsAudio.totalTime = totalTime;
      commentsAudio.fileSize = tempFile.fileSize;
      commentsAudio.startDate = "00:00";
      commentsAudio.totalDate = util.digitalFormatTime(totalTime);
      commentsAudio.isBoFang = "0";
      _this.setData({
        commentsAudio: commentsAudio
      })
    } else {
      /*_this.setData({
        commentsAudio: {}
      })*/
    }
  },

  /**
   * 删除录音：评论
   */
  deleteCommentsRecorder: function () {
    var _this = this;
    _this.setData({
      ["commentsAudio.isVoiceDialogShow"]: false,
      commentsAudio: {}
    })
    _this.doClearInterval();
    recorderManager.stop();
  },

  /**
   * 清空录音：评论
   */
  clearCommentsRecorder: function () {
    var _this = this;
    _this.setData({
      ["commentsAudio.isVoiceDialogShow"]: false
    })
    _this.doClearInterval();
    recorderManager.stop();

    setTimeout(function () {
      _this.commentsAudioTap();
    }, 100)
  },

  /**
   * 定时器计算录音时间：评论
   */
  doCommentsRecordInterval: function () {
    var _this = this;
    if (recordInterval == null) {
      recordInterval = setInterval(function () {
        var commentsAudio = _this.data.commentsAudio;
        var totalTime = commentsAudio.totalTime + 1;
        var totalDate = util.digitalFormatTime(totalTime);
        _this.setData({
          ["commentsAudio.totalTime"]: totalTime,
          ["commentsAudio.totalDate"]: totalDate
        });
      }, 1000);
    }
  },

  /**
   * 暂停录音：评论
   */
  commentsPauseRecorder: function (e) {
    var _this = this;
    _this.setData({
      ["commentsAudio.playState"]: "2"
    });
    recorderManager.pause();
    _this.doClearInterval();
  },

  /**
   * 继续录音：评论
   */
  commentsResumeRecorder: function (e) {
    var _this = this;
    _this.setData({
      ["commentsAudio.playState"]: "1"
    })
    recorderManager.resume();
    _this.doCommentsRecordInterval();
  },

  /**
   * 停止录音：评论
   */
  commentsStopRecorder: function (e) {
    var _this = this;
    recorderManager.stop();
    recorderManager.onStop((res) => {
      _this.commentsStopRecorderExecute(res);
    });
  },

  /**
   * 播放或暂停动作
   */
  commentsAudioBoFang: function (e) {
    var _this = this;
    var src = _this.data.commentsAudio.src;
    var title = _this.data.commentsAudio.title;
    var currentTime = _this.data.commentsAudio.currenttime;
    var isBoFang = _this.data.commentsAudio.isBoFang;
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (isBoFang == "1") {
      // 切换至暂停状态
      backgroundAudioManager.pause();//暂停播放音乐
      _this.setData({
        ["commentsAudio.isBoFang"]: "0"
      });
    } else {
      // 切换至播放状态
      wx.stopBackgroundAudio();//暂停正在播放音乐
      backgroundAudioManager.startTime = currentTime;//设置音乐开始时间
      backgroundAudioManager.title = title;
      backgroundAudioManager.src = src;
      backgroundAudioManager.play();
      //    背景音频自然播放结束事件
      backgroundAudioManager.onEnded(function () {
        _this.setData({
          ["commentsAudio.currentTime"]: 0,
          ["commentsAudio.isBoFang"]: "0",
          ["commentsAudio.startDate"]: "00:00"
        });
      })
      //背景音频播放进度更新事件
      backgroundAudioManager.onTimeUpdate(function (callback) {
        var position = Math.round(backgroundAudioManager.currentTime);
        var voiceStartDate = util.digitalFormatTime(position);
        _this.setData({
          ["commentsAudio.currentTime"]: backgroundAudioManager.currentTime,
          ["commentsAudio.startDate"]: voiceStartDate
        });
      })

      _this.setData({
        ["commentsAudio.isBoFang"]: "1"
      });
    }
  },

  /**
  * 发表评论
  */
  submitComments: function () {
    var _this = this;
    var commentsTextarea = _this.data.commentsTextarea;
    var commentsAudio = _this.data.commentsAudio;
    if (!(commentsTextarea.length > 0 || (commentsAudio.state != null && commentsAudio.state.length > 0))) {
      util.dialogAlert("评论内容不能为空");
      return false;
    } else if (commentsAudio.state != null && commentsAudio.state == "1") {
      util.dialogAlert("正在录制音频中");
      return false;
    }
    wx.showLoading({
      title: '保存中',
    })
    _this.setData({
      isSubmitAll: false
    })
    var uploadInfoList = [];
    if (commentsAudio.state != null && commentsAudio.state == "2" && commentsAudio.isupload) {
      var uploadInfo = {};
      uploadInfo.type = "2";// 类型:1图片  2音频  3视频
      uploadInfo.filePath = commentsAudio.src;
      uploadInfoList.push(uploadInfo);
    }
    if (uploadInfoList.length > 0) {
      // 开始请求:要先上传
      _this.uploadCommentsFileQuery(uploadInfoList, 0);
    } else {
      _this.saveComments();
    }
  },

  /**
   * 上传评论
   */
  uploadCommentsFileQuery: function (data, queryIndex) {
    var _this = this;
    var queryData = data[queryIndex];
    var queryUrl = "";
    switch (queryData.type) {
      case "2":
        // 音频
        queryUrl = api.File_doAudioUpload;
        break;
    }
    wx.uploadFile({
      url: queryUrl,
      filePath: queryData.filePath,
      name: 'file',
      formData: {
        "type": "5"
      },
      success(res) {
        var data = JSON.parse(res.data);
        if (data.code == 200) {
          var ip = data.result.ip;
          var path = data.result.path;
          switch (queryData.type) {
            case "2":
              // 音频
              _this.setData({
                ["commentsAudio.ip"]: ip,
                ["commentsAudio.src"]: path
              })
              break;
          }
        }
      },
      fail(res) {
        // 失败
      },
      complete(res) {
        // 结束：
        if (queryIndex < data.length - 1) {
          // 图片未上传完成，继续上传
          queryIndex++;
          _this.uploadFileQuery(data, queryIndex);
        } else {
          // 上传完成，执行save请求
          _this.saveComments();
        }
      }
    })
  },

  /**
   * save评论请求
   */
  saveComments: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    var saveCommentsIndex = _this.data.saveCommentsIndex;
    util.post(api.fetchToken()).then(function (res) {
      if (res.access_token != '') {
        return Promise.resolve({
          access_token: res.access_token
        });
      }
    }).then(function (res) {
      var data = {};
      data.openid = openid;
      data.access_token = res.access_token;
      data.circleid = _this.data.circleid;
      data.diaryid = _this.data.diaryInfoList[saveCommentsIndex].ordDiary.id;
      data.replyCommentsid = _this.data.replyCommentsid;
      data.mainReplyCommentsid = _this.data.mainReplyCommentsid;
      data.diaryText = _this.data.commentsTextarea;
      if (_this.data.commentsAudio.state != null && _this.data.commentsAudio.state == "2") {
        data.diaryAudio = JSON.stringify(_this.data.commentsAudio);
      }
      util.post(api.Home_SaveOrUpdateOrdDiaryCommentsApiUrl, data).then(function (res) {
        wx.hideLoading();
        _this.setData({
          isSubmitAll: false
        })
        if (res.code == 200) {
          _this.getDiaryInfoByDiaryId(saveCommentsIndex);
          _this.commentsDialogClose();
          var energyInfoResults = res.result.energyInfoResults;
          if (energyInfoResults == true) {
            _this.setData({
              diary_commones_dialog: true
            })
            setTimeout(() => {
              _this.setData({
                diary_commones_dialog: false
              })
            }, 2000);
          }
        }
      })
    })
  },

  /**
   * 评论的右侧点击显示底部的弹窗
   */
  commonsBottomShow: function (e) {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    var id = e.currentTarget.dataset.id;
    var mainid = e.currentTarget.dataset.mainid;
    var nickname = e.currentTarget.dataset.nickname;
    var saveCommentsIndex = e.currentTarget.dataset.index;
    var commonsopenid = e.currentTarget.dataset.commonsopenid;
    var diaryCommentsid = e.currentTarget.dataset.deleteid;
    var thisInterestJoinUser = _this.data.thisInterestJoinUser;
    var isCommonsDelete = false;
    if (thisInterestJoinUser.identitytype == 1 || thisInterestJoinUser.identitytype == 2 || thisInterestJoinUser.identitytype == 3) {
      isCommonsDelete = true;
    }
    if (commonsopenid == openid) {
      isCommonsDelete = true;
    }
    _this.setData({
      commonsBottomShow: true,
      replyCommentsid: id,
      mainReplyCommentsid: mainid,
      replyCommentNickname: nickname,
      saveCommentsIndex: saveCommentsIndex,
      isCommonsDelete: isCommonsDelete,
      diaryCommentsid: diaryCommentsid
    })
  },

  /**
   * 评论的右侧点击关闭底部的弹窗
   */
  commonsBottomClose: function () {
    var _this = this;
    _this.setData({
      commonsBottomShow: false,
      replyCommentsid: 0,
      mainReplyCommentsid: 0,
      replyCommentNickname: '',
      saveCommentsIndex: ''
    })
  },

  /**
   * 播放录音：评论
   */
  ordCommonsBoFang: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var yindex = e.currentTarget.dataset.yindex;
    var xindex = e.currentTarget.dataset.xindex;
    var zindex = e.currentTarget.dataset.zindex;
    var ordCommonsAudio = {};
    if (parseInt(zindex) >= 0) {
      ordCommonsAudio = _this.data.diaryInfoList[index].commentsList[yindex].replyCommentsList[zindex].replyCommentsAudioList[xindex];
    } else {
      ordCommonsAudio = _this.data.diaryInfoList[index].commentsList[yindex].replyCommentsAudioList[xindex];
    }
    var isBoFang = ordCommonsAudio.isBoFang;
    var ip = ordCommonsAudio.ip;
    var name = ordCommonsAudio.name;
    var currentTime = ordCommonsAudio.currentTime;
    var audiourl = ordCommonsAudio.url;
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (isBoFang == "1") {
      // 切换至暂停状态
      wx.pauseBackgroundAudio();//暂停播放音乐
      backgroundAudioManager.pause();//暂停播放音乐
      if (parseInt(zindex) >= 0) {
        _this.setData({
          ["diaryInfoList[" + index + "].commentsList[" + yindex + "].replyCommentsList[" + zindex + "].replyCommentsAudioList[" + xindex + "].isBoFang"]: 0
        });
      } else {
        _this.setData({
          ["diaryInfoList[" + index + "].commentsList[" + yindex + "].replyCommentsAudioList[" + xindex + "].isBoFang"]: 0
        });
      }
    } else {
      // 切换至播放状态
      wx.stopBackgroundAudio();////暂停正在播放音乐
      backgroundAudioManager.startTime = currentTime;//设置音乐开始时间
      backgroundAudioManager.title = name;
      backgroundAudioManager.src = ip + audiourl;
      backgroundAudioManager.play();
      //    背景音频自然播放结束事件
      backgroundAudioManager.onEnded(function () {
        if (parseInt(zindex) >= 0) {
          _this.setData({
            ["diaryInfoList[" + index + "].commentsList[" + yindex + "].replyCommentsList[" + zindex + "].replyCommentsAudioList[" + xindex + "].isBoFang"]: 0,
            ["diaryInfoList[" + index + "].commentsList[" + yindex + "].replyCommentsList[" + zindex + "].replyCommentsAudioList[" + xindex + "].currentTime"]: 0
          });
        } else {
          _this.setData({
            ["diaryInfoList[" + index + "].commentsList[" + yindex + "].replyCommentsAudioList[" + xindex + "].isBoFang"]: 0,
            ["diaryInfoList[" + index + "].commentsList[" + yindex + "].replyCommentsAudioList[" + xindex + "].currentTime"]: 0
          });
        }
      })
      //背景音频播放进度更新事件
      backgroundAudioManager.onTimeUpdate(function (callback) {
        if (parseInt(zindex) >= 0) {
          _this.setData({
            ["diaryInfoList[" + index + "].commentsList[" + yindex + "].replyCommentsList[" + zindex + "].replyCommentsAudioList[" + xindex + "].currentTime"]: backgroundAudioManager.currentTime
          });
        } else {
          _this.setData({
            ["diaryInfoList[" + index + "].commentsList[" + yindex + "].replyCommentsAudioList[" + xindex + "].currentTime"]: backgroundAudioManager.currentTime
          });
        }
      })

      if (parseInt(zindex) >= 0) {
        _this.setData({
          ["diaryInfoList[" + index + "].commentsList[" + yindex + "].replyCommentsList[" + zindex + "].replyCommentsAudioList[" + xindex + "].isBoFang"]: 1
        });
      } else {
        _this.setData({
          ["diaryInfoList[" + index + "].commentsList[" + yindex + "].replyCommentsAudioList[" + xindex + "].isBoFang"]: 1
        });
      }
    }
  },

  /**
   * 删除评论
   */
  commentsDelete: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    var replyCommentsid = _this.data.replyCommentsid;
    var saveCommentsIndex = _this.data.saveCommentsIndex;
    if (openid != null && openid != "") {
      wx.showLoading({
        title: "删除中"
      })
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        data.circleid = _this.data.circleid;
        data.diaryid = _this.data.diaryInfoList[saveCommentsIndex].ordDiary.id;
        data.diaryCommentsid = _this.data.diaryCommentsid;
        util.post(api.Home_DeleteOrdDiaryCommentsApiUrl, data).then(function (res) {
          wx.hideLoading();
          if (res.code == 200) {
            _this.getDiaryInfoByDiaryId(saveCommentsIndex);
            _this.commonsBottomClose();
          }
        });
      })
    }
  },

  setShow: function () {
    var _this = this;
    var setShow = _this.data.setShow;
    if (setShow) {
      _this.setData({
        setShow: false,
        maskLayerShow: false
      })
    } else {
      _this.setData({
        setShow: true,
        maskLayerShow: true
      })
    }
  },

  /**
   * 日记操作的底部展示弹窗
   */
  diaryOperationShow: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var diaryInfo = _this.data.diaryInfoList[index];
    var isPlacedtop = diaryInfo.ordDiary.isPlacedtop;// 是否加精
    var id = diaryInfo.ordDiary.id;
    var diaryOperationShowInfo = { "index": index, "isPlacedtop": isPlacedtop, "ordDiaryid": id, "diaryInfo": diaryInfo };
    _this.setData({
      diaryOperationShow: true,
      diaryOperationShowInfo: diaryOperationShowInfo
    })
  },

  /**
   * 日记操作的底部关闭弹窗
   */
  diaryOperationClose: function () {
    var _this = this;
    _this.setData({
      updateGroupid: "",
      groupingDialogShow: false,
      diaryOperationShow: false,
      diaryOperationShowInfo: {}
    })
  },

  /**
   * 校验圈主是否有验证手机号
   */
  checkMainCirclePhone: function () {
    var _this = this;
    var thisInterestJoinUser = _this.data.thisInterestJoinUser;
    if (thisInterestJoinUser.identitytype == 1) {
      // 当前用户是圈主
      var mobile = _this.data.mainUser.mobile;
      if (mobile == null || mobile.length <= 0) {
        wx.login({
          success: function (res) {
            // 需要验证手机号
            _this.setData({
              authPhoneDialogShow: true,
              login_code: res.code
            })
          },
          fail: function (err) {
            reject(err);
          }
        });
      } else {
        var mainUserSetup = _this.data.mainUserSetup;
        if (mainUserSetup.circleOneCreate == 0) {
          // 圈主第一次进入圈子，弹出第一步
          _this.setData({
            firstSteplayerShow: true,
            maskLayerShow: true
          })
        }
      }
    }
  },

  /**
   * 关闭验证手机号的弹窗
   */
  authPhoneDialogClose: function () {
    var _this = this;
    _this.setData({
      authPhoneDialogShow: false,
      login_code: ""
    });
    var mainUserSetup = _this.data.mainUserSetup;
    if (mainUserSetup.circleOneCreate == 0) {
      // 圈主第一次进入圈子，弹出第一步
      _this.setData({
        firstSteplayerShow: true,
        maskLayerShow: true
      })
    }
  },

  /**
   * 筛选弹窗
   */
  screeningDialogShow: function () {
    var _this = this;
    _this.setData({
      screeningDialogShow: true
    })
  },

  /**
   * 筛选取消条件
   */
  screeningDialogClose: function () {
    var _this = this;
    var screeningData = { "isreview": "", "members": "", "starttimevalue": "", "starttimetext": "选择开始时间", "starttimearray": [0, 0, 0], "endtimevalue": "", "endtimetext": "选择结束时间", "startendarray": [0, 0, 0], "groupid": "", "endTimePickerDisabled": false, "startTimePickerDisabled": false, "select_openid": "" };
    _this.setData({
      screeningData: screeningData,
      screeningDialogShow: false,
      diaryInfoPageNum: 1,
      diaryInfoPageSize: 10,
      diaryInfoList: []
    })
    _this.getDiaryInfo();
  },

  /**
   * 筛选弹窗关闭
   */
  screeningDialogClose2: function () {
    var _this = this;
    _this.setData({
      screeningDialogShow: false
    })
  },

  /**
   * 筛选条件点击事件
   */
  screeningDataBindtap: function (e) {
    var _this = this;
    var id = e.currentTarget.dataset.id;
    var type = e.currentTarget.dataset.type;
    var screeningData = _this.data.screeningData;
    switch (type) {
      case "isreview":
        // 筛选是否点评
        var isreview = screeningData.isreview;
        if (isreview == id) {
          screeningData.isreview = "";
        } else {
          screeningData.isreview = id;
        }
        break;
      case "members":
        // 筛选新成员
        var members = screeningData.members;
        if (members == id) {
          screeningData.members = "";
        } else {
          screeningData.members = id;
        }
        break;
      case "group":
        // 分组
        var groupid = screeningData.groupid;
        if (groupid == id) {
          screeningData.groupid = "";
        } else {
          screeningData.groupid = id;
        }
        break;
    }
    _this.setData({
      screeningData: screeningData
    })
  },

  /**
   * 筛选开始时间
   */
  startTimeBindChange: function (e) {
    var _this = this;
    var value = e.detail.value;
    var screeningData = _this.data.screeningData;
    var screeningTimeArray = _this.data.screeningTimeArray;
    var dayText = screeningTimeArray[0][value[0]].text;
    var dayValue = screeningTimeArray[0][value[0]].value;
    var hourText = screeningTimeArray[1][value[1]].text;
    var hourValue = screeningTimeArray[1][value[1]].value;
    var minuteText = screeningTimeArray[2][value[2]].text;
    var minuteValue = screeningTimeArray[2][value[2]].value;
    var starttimevalue = dayValue + " " + hourValue + ":" + minuteValue + ":00";
    var starttimetext = dayText + " " + hourText + ":" + minuteText;
    var starttimearray = value;
    screeningData.starttimevalue = starttimevalue;
    screeningData.starttimetext = starttimetext;
    screeningData.starttimearray = starttimearray;
    _this.setData({
      screeningData: screeningData
    })
  },

  /**
   * 筛选结束时间
   */
  endTimeBindChange: function (e) {
    var _this = this;
    var value = e.detail.value;
    var screeningData = _this.data.screeningData;
    var screeningTimeArray = _this.data.screeningTimeArray;
    var dayText = screeningTimeArray[0][value[0]].text;
    var dayValue = screeningTimeArray[0][value[0]].value;
    var hourText = screeningTimeArray[1][value[1]].text;
    var hourValue = screeningTimeArray[1][value[1]].value;
    var minuteText = screeningTimeArray[2][value[2]].text;
    var minuteValue = screeningTimeArray[2][value[2]].value;
    var endtimevalue = dayValue + " " + hourValue + ":" + minuteValue + ":59";
    var endtimetext = dayText + " " + hourText + ":" + minuteText;
    var endtimearray = value;
    screeningData.endtimevalue = endtimevalue;
    screeningData.endtimetext = endtimetext;
    screeningData.endtimearray = endtimearray;
    _this.setData({
      screeningData: screeningData
    })
  },

  /**
   * 筛选的开始时间图标点击事件
   */
  startTimeIconBindTap: function () {
    var _this = this;
    var screeningData = _this.data.screeningData;
    screeningData.startTimePickerDisabled = true;
    _this.setData({
      screeningData: screeningData
    })

    screeningData.starttimevalue = "";
    screeningData.starttimetext = "选择开始时间";
    screeningData.starttimearray = [0, 0, 0];
    screeningData.startTimePickerDisabled = false;
    _this.setData({
      screeningData: screeningData
    })
  },

  /**
   * 筛选的结束时间图标点击事件
   */
  endTimeIconBindTap: function () {
    var _this = this;
    var screeningData = _this.data.screeningData;
    screeningData.endTimePickerDisabled = true;
    _this.setData({
      screeningData: screeningData
    })

    screeningData.endtimevalue = "";
    screeningData.endtimetext = "选择结束时间";
    screeningData.endtimearray = [0, 0, 0];
    screeningData.endTimePickerDisabled = false;
    _this.setData({
      screeningData: screeningData
    })
  },

  /**
   * 获取组员信息
   */
  getInterestJoin: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    var interestJoinPageNum = _this.data.interestJoinPageNum;
    var interestJoinPageSize = _this.data.interestJoinPageSize;
    var data = {};
    data.circleid = _this.data.circleid;
    data.pageNum = interestJoinPageNum;
    data.pageSize = interestJoinPageSize;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        data.openid = openid;
        data.access_token = res.access_token;
        _this.getInterestJoinQuery(api.Home_GetInterestJoinApiUrl, data);
      })
    } else {
      _this.getInterestJoinQuery(api.Home_GetInterestJoinUrl, data);
    }
  },

  /**
   * 获取组员：请求
   */
  getInterestJoinQuery: function (url, data) {
    var _this = this;
    util.post(url, data).then(function (res) {
      if (res.code == 200) {
        var interestJoinTotalPages = res.result.pages;
        var interestJoinTotalCount = res.result.count;
        var resultList = res.result.list;
        var list = _this.data.interestJoinList;
        for (var i = 0; i < resultList.length; i++) {
          list.push(resultList[i]);
        }
        _this.setData({
          interestJoinList: list,
          interestJoinTotalPages: interestJoinTotalPages,
          interestJoinTotalCount: interestJoinTotalCount
        })
      }
    });
  },

  /**
   * 获取分组信息
   */
  getGroup: function () {
    var _this = this;
    var circleid = _this.data.circleid;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.circleid = circleid;
        data.openid = openid;
        data.access_token = res.access_token;
        util.post(api.Home_GetGroupApiUrl, data).then(function (res) {
          if (res.code == 200) {
            var list = res.result.list;
            _this.setData({
              groupList: list
            })
          }
        });
      })
    }
  },

  /**
   * 置顶加精或者取消加精
   */
  updateDiaryPlacedtop: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var diaryOperationShowInfo = _this.data.diaryOperationShowInfo;
        var ordDiaryid = diaryOperationShowInfo.ordDiaryid;
        var circleid = _this.data.circleid;
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        data.circleid = circleid;
        data.ordDiaryid = ordDiaryid;
        util.post(api.Home_UpdateDiaryPlacedtopApiUrl, data).then(function (res) {
          if (res.code == 200) {
            _this.setData({
              ["diaryInfoList[" + diaryOperationShowInfo.index + "].ordDiary.isPlacedtop"]: res.result.count
            })
            _this.diaryOperationClose();
          }
        })
      })
    }
  },

  /**
   * 设置分组
   */
  setUpGroup: function () {
    var _this = this;
    var groupList = _this.data.groupList;
    var updateGroupid = _this.data.diaryOperationShowInfo.diaryInfo.ordInterestJoin.groupid;
    if (groupList.length > 0) {
      // 有分组，展示分组
      _this.setData({
        diaryOperationShow: false,
        groupingDialogShow: true,
        updateGroupid: updateGroupid
      })
    } else {
      // 无分组
      _this.diaryOperationClose();
      _this.setData({
        groupingEmptyDialogShow: true
      })
    }
  },

  /**
   * 无分组弹窗关闭
   */
  groupingEmptyDialogClose: function () {
    var _this = this;
    _this.setData({
      groupingEmptyDialogShow: false
    })
  },

  /**
   * 无分组弹窗确定
   */
  groupingEmptyDialogConfirm: function () {
    var _this = this;
    _this.setData({
      groupingEmptyDialogShow: false
    })
    _this.navigateToGroup();
  },

  /**
   * 跳转到搜索成员页面
   */
  navigateToGroupSearch: function () {
    var _this = this;
    var circleid = _this.data.circleid;
    wx.navigateTo({
      url: '../circleinteraction/group/groupSearch/groupSearch?circleid=' + circleid,
    })
  },

  /**
   * 跳转到分组的页面
   */
  navigateToGroup: function () {
    var _this = this;
    var circleid = _this.data.circleid;
    var index = _this.data.diaryOperationShowInfo.index;
    _this.setData({
      otherPageIndex: index
    })
    _this.screeningDialogClose2();
    wx.navigateTo({
      url: '../circleinteraction/group/group?circleid=' + circleid,
    })
  },

  /**
   * 跳转到后台管理页面
   */
  navigateToFoundationsetup: function () {
    var _this = this;
    var circleid = _this.data.circleid;
    //_this.setShow();
    _this.setData({
      setShow: false,
      maskLayerShow: false,
      circleOperationShow: false
    })
    wx.navigateTo({
      url: '../circleinteraction/backstagemanage/backstagemanage?circleid=' + circleid,
    })
  },

  /**
   * 跳转到能量值页面
   */
  navigateToCircleenergy: function () {
    var _this = this;
    var circleid = _this.data.circleid;
    wx.navigateTo({
      url: '../circleinteraction/circleenergy/circleenergy?id=' + circleid,
    })
  },

  /**
   * 成员设置分组选中事件
   */
  groupListBindTap: function (e) {
    var _this = this;
    var updateGroupid = e.currentTarget.dataset.id;
    _this.setData({
      updateGroupid: updateGroupid
    })
  },

  /**
   * 设置分组提交
   */
  groupingDialogConfirm: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var updateGroupid = _this.data.updateGroupid;
        var diaryOperationShowInfo = _this.data.diaryOperationShowInfo;
        var joinid = diaryOperationShowInfo.diaryInfo.ordInterestJoin.joinid;
        var data = {};
        data.joinid = joinid;
        data.groupid = updateGroupid;
        data.circleid = _this.data.circleid;
        data.openid = openid;
        data.access_token = res.access_token;
        util.post(api.Home_UpdateJoinUserInfoApiUrl, data).then(function (res) {
          if (res.code == 200) {
            _this.getDiaryInfoByDiaryId(diaryOperationShowInfo.index);
            _this.diaryOperationClose();
            _this.getGroup();
          }
        })
      })
    }
  },

  /**
   * 跳转到视频播放页面：日记
   */
  navigateToVideo: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var yindex = e.currentTarget.dataset.yindex;
    var diaryInfo = _this.data.diaryInfoList[index];
    var video = diaryInfo.imageVideoList[yindex];
    var diaryid = diaryInfo.ordDiary.id;
    var src = video.ip + video.url;
    wx.navigateTo({
      url: "../../../../../../pages/home/video/video?state=1&type=2&id=" + diaryid + "&src=" + src
    })
  },

  /**
   * 预览图片：日记
   */
  previewImage: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var yindex = e.currentTarget.dataset.yindex;
    var diaryInfo = _this.data.diaryInfoList[index];
    var imageList = diaryInfo.imageVideoList;
    var urls = [];
    var current = diaryInfo.imageVideoList[yindex].ip + diaryInfo.imageVideoList[yindex].url;
    for (var i = 0; i < imageList.length; i++) {
      if (imageList[i].imageVideoType == "1") {
        urls.push(imageList[i].ip + imageList[i].url);
      }
    }
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },

  /**
   * 预览图片：点评
   */
  previewReviewImage: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var yindex = e.currentTarget.dataset.yindex;
    var xindex = e.currentTarget.dataset.xindex;
    var ordReviewImageList = _this.data.diaryInfoList[index].ordReviewList[yindex].ordReviewImageList;
    var urls = [];
    var current = ordReviewImageList[xindex].ip + ordReviewImageList[xindex].url;
    for (var i = 0; i < ordReviewImageList.length; i++) {
      urls.push(ordReviewImageList[i].ip + ordReviewImageList[i].url);
    }
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },

  /**
   * 计算高度
   */
  calculateHeight: function () {
    var _this = this;
    var diaryInfoList = _this.data.diaryInfoList;
    for (var i = 0; i < diaryInfoList.length; i++) {
      var diaryTextList = diaryInfoList[i].diaryTextList;
      for (var y = 0; y < diaryTextList.length; y++) {
        var id = "#diaryText_" + i + "_" + y;
        var query = wx.createSelectorQuery();
        query.select(id).boundingClientRect(function (rect) {
          var id = rect.id;
          var diaryInfoIndex = id.split("_")[1];
          var diaryTextIndex = id.split("_")[2];
          var height = rect.height;
          if (height > 72) {
            _this.setData({
              ["diaryInfoList[" + diaryInfoIndex + "].diaryTextList[" + diaryTextIndex + "].isOverflow"]: true
            })
          }
        }).exec();
      }
    }
  },

  /**
   * 文字的全文展开
   */
  diaryTextOverflow: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var yindex = e.currentTarget.dataset.yindex;
    _this.setData({
      ["diaryInfoList[" + index + "].diaryTextList[" + yindex + "].isOverflow"]: false
    })
  },

  /**
   * 跳转到公众号展示页面：日记
   */
  navigateToWebView: function (e) {
    var ip = e.currentTarget.dataset.ip;
    var text = e.currentTarget.dataset.text;
    var type = e.currentTarget.dataset.type;
    if (type == 1) {
      wx.navigateTo({
        url: '../../../../../../pages/home/webView/webView?src=' + text,
      })
    } else {
      wx.downloadFile({
        url: ip + text,
        success: function (res) {
          var filePath = res.tempFilePath;
          wx.openDocument({
            filePath: filePath,
            success: function (res) {
            }
          })
        }
      })
    }
  },

  /**
   * 返回首页
   */
  redirectToHome: function () {
    wx.switchTab({
      url: '../../../../../../pages/home/home'
    })
  },

  /**
   * 获取单个单个日记详情
   */
  getDiaryInfoByDiaryId: function (index) {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    var data = {};
    data.circleid = _this.data.circleid;
    data.ordDiaryid = _this.data.diaryInfoList[index].ordDiary.id;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        data.openid = openid;
        data.access_token = res.access_token;
        _this.getDiaryInfoByDiaryIdQuery(index, api.Home_GetDiaryInfoByDiaryIdApiUrl, data);
      })
    } else {
      _this.getDiaryInfoByDiaryIdQuery(index, api.Home_GetDiaryInfoByDiaryIdUrl, data);
    }
  },

  /**
   * 获取单个日记详情：请求
   */
  getDiaryInfoByDiaryIdQuery: function (index, url, data) {
    var _this = this;
    util.post(url, data).then(function (res) {
      if (res.code == 200) {
        var json = res.result.json;
        var diaryTextList = _this.data.diaryInfoList[index].diaryTextList;
        json.diaryTextList = diaryTextList;
        _this.setData({
          ["diaryInfoList[" + index + "]"]: json
        });

        var updateGroupid = _this.data.updateGroupid;
        if (parseInt(updateGroupid) > 0) {
          _this.setData({
            updateGroupid: json.ordInterestJoin.groupid
          })
        }
      }
    });
  },

  /**
   * 删除弹窗：展开
   */
  deleteDiaryDialogShow: function () {
    var _this = this;
    _this.setData({
      deleteDiaryDialogShow: true,
      diaryOperationShow: false
    })
  },

  /**
   * 删除弹窗：关闭
   */
  deleteDiaryDialogClose: function () {
    var _this = this;
    _this.setData({
      deleteDiaryDialogShow: false,
      diaryOperationShow: false,
      diaryOperationShowInfo: {}
    })
  },

  /**
   * 删除弹窗：提交
   */
  deleteDiaryDialogConfirm: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    var diaryInfoList = _this.data.diaryInfoList;
    var diaryOperationShowInfo = _this.data.diaryOperationShowInfo;
    var index = diaryOperationShowInfo.index;
    var ordDiaryid = diaryOperationShowInfo.ordDiaryid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        data.ordDiaryid = ordDiaryid;
        data.circleid = _this.data.circleid;
        util.post(api.Home_DeleteDiaryByDiaryIdApiUrl, data).then(function (res) {
          if (res.code == 200) {
            diaryInfoList.splice(index, 1);
            _this.setData({
              diaryInfoList: diaryInfoList
            })
            _this.deleteDiaryDialogClose();
          }
        })
      })
    }
  },

  /**
   * 日记详情
   */
  toDiaryDetails: function (e) {
    var _this = this;
    _this.diaryOperationClose();
    var circleid = _this.data.circleid;
    var index = e.currentTarget.dataset.index;
    var diaryid = _this.data.diaryInfoList[index].ordDiary.id;
    _this.setData({
      otherPageIndex: index
    })
    wx.navigateTo({
      url: '../circleinteraction/diaryDetails/diaryDetails?circleid=' + circleid + '&diaryid=' + diaryid
    })
  },

  /**
   * 去契约页面
   */
  navigateToCreatecontract: function () {
    var _this = this;
    var circleid = _this.data.circleid;
    wx.navigateTo({
      url: '../createcontract/createcontract?circleid=' + circleid
    })
  },

  /**
   * 语音拒绝授权的提示弹窗关闭
   */
  audioOauhRefusedDialogClose: function () {
    var _this = this;
    _this.setData({
      audioOauhRefusedDialogShow: false
    })
  },

  /**
   * 语音拒绝授权的提示弹窗确认动作
   */
  audioOauhRefusedDialogSuccess: function () {
    var _this = this;
    wx.openSetting({
      success: function (data) {
        if (data.authSetting["scope.record"] == true) {
          // 授权成功
          _this.audioOauhRefusedDialogClose();
        } else {
          // 授权失败
          _this.audioOauhRefusedDialogClose();
        }
      }
    })
  },

  /**
   * 进入用户主页
   */
  navigateToPersonhome: function (e) {
    var openid = e.currentTarget.dataset.openid;
    wx.navigateTo({
      url: '../../../personhome/personhome?openid=' + openid
    })
  },

  notToDiaryDetails: function () {

  },

  /**
   * 获取圈子的推荐信息
   */
  getCircleRecommendInfo: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    var circleid = _this.data.circleid;
    var circleRecommendPageNum = _this.data.circleRecommendPageNum;
    var circleRecommendPageSize = _this.data.circleRecommendPageSize;
    var thisInterestJoinUser = _this.data.thisInterestJoinUser;
    var identitytype = thisInterestJoinUser == null ? 0 : thisInterestJoinUser.identitytype;
    var data = {};
    data.circleid = circleid;
    data.pageNum = circleRecommendPageNum;
    data.pageSize = circleRecommendPageSize;
    data.isObtainSystemRecommend = "1";
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        data.openid = openid;
        data.access_token = res.access_token;
        _this.getCircleRecommendInfoQuery(api.Home_GetCircleRecommendInfoApiUrl, data);
      })
    } else {
      _this.getCircleRecommendInfoQuery(api.Home_GetCircleRecommendInfoUrl, data);
    }
  },

  /**
   * 获取圈子的推荐信息：请求
   */
  getCircleRecommendInfoQuery: function (url, data) {
    var _this = this;
    util.post(url, data).then(function (res) {
      if (res.code == 200) {
        var resultList = res.result.list;
        var list = _this.data.circleRecommendList;
        for (var i = 0; i < resultList.length; i++) {
          var optimalMoneyResult = resultList[i].optimalMoneyResult;
          if (optimalMoneyResult != null) {
            var preferentialAmountDetails = optimalMoneyResult.preferentialAmountDetails;
            if (preferentialAmountDetails != null && preferentialAmountDetails.length > 0) {
              resultList[i].optimalMoneyResult.preferentialAmountDetails = JSON.parse(preferentialAmountDetails);
            }
          }
          list.push(resultList[i]);
        }
        _this.setData({
          circleRecommendList: list,
          isCircleRecommendQuery: resultList.length > 0 ? true : false
        })
      }
    });
  },

  /**
   * 橙贝弹窗的关闭
   */
  chengbeiDialogClose: function () {
    var _this = this;
    var chengbeiDialog = { "show": false, "size": 0, "count": 0, "shareDialogShow": false };
    _this.setData({
      chengbeiDialog: chengbeiDialog
    })
    _this.shareDialogShow();
  },

  /**
   * 圈子分享成功的弹窗
   */
  shareDialogShow: function () {
    var _this = this;
    _this.setData({
      ["chengbeiDialog.shareDialogShow"]: true
    })
    setTimeout(function () {
      _this.setData({
        ["chengbeiDialog.shareDialogShow"]: false
      })
    }, 2000)
  },

  /**
   * 成长：打开弹窗
   */
  seedDialogShow: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var seedDialog = _this.data.seedDialog;
    seedDialog.show = true;
    seedDialog.index = index;
    seedDialog.diaryInfo = _this.data.diaryInfoList[index];
    _this.setData({
      seedDialog: seedDialog
    })
  },

  /**
   * 成长：关闭弹窗
   */
  seedDialogClose: function () {
    var _this = this;
    var seedDialog = { "show": false, "index": "", "seedRulesDialogShow": false, "diaryInfo": {} };
    _this.setData({
      seedDialog: seedDialog
    })
  },

  /**
   * 种子法则
   */
  seedRulesDialogShow: function () {
    var _this = this;
    _this.setData({
      ["seedDialog.seedRulesDialogShow"]: !_this.data.seedDialog.seedRulesDialogShow
    })
  },


  /**
   * 进入圈子详情页面
   */
  navigateToCircleInfo: function (e) {
    var _this = this;
    var circleid = e.currentTarget.dataset.circleid;
    var openid = app.globalData.logininfo.openid;
    var data = {};
    data.circleid = circleid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        data.openid = openid;
        data.access_token = res.access_token;
        _this.userIsCircleJoinQuery(api.Home_UserIsCircleJoinApiUrl, data);
      })
    } else {
      _this.userIsCircleJoinQuery(api.Home_UserIsCircleJoinUrl, data);
    }
  },

  /**
   * 校验用户是否为已加入的圈子：请求
   */
  userIsCircleJoinQuery: function (url, data) {
    var _this = this;
    util.post(url, data).then(function (res) {
      var userIsCircleJoin = false;
      if (res.code == 200) {
        userIsCircleJoin = res.result.userIsCircleJoin;
      }
      if (userIsCircleJoin) {
        // 已加入
        wx.navigateTo({
          url: '../circleinteraction/circleinteraction?circleid=' + data.circleid,
        })
      } else {
        // 未加入
        wx.navigateTo({
          url: '../circledetails/circledetails?circleid=' + data.circleid + "&distributionOpenid=" + _this.data.mainUser.openid,
        })
      }
    });
  },

  /**
   * 修改圈子的预览次数
   */
  addIspreview: function () {
    var _this = this;
    var data = {};
    data.circleid = _this.data.circleid;
    util.post(api.Interest_addIspreview, data).then(function (res) { })
  },

  /**
   * 使用微信内置地图查看位置
   */
  wxGetLocation: function (e) {
    var name = e.currentTarget.dataset.name;
    var address = e.currentTarget.dataset.address;
    var latitude = e.currentTarget.dataset.latitude;
    var longitude = e.currentTarget.dataset.longitude;
    wx.openLocation({
      latitude: latitude,//要去的纬度-地址
      longitude: longitude,//要去的经度-地址
      name: name,
      address: address
    })
  },

  /**
   * 跳转到主题详情
   */
  themeDetail: function (e) {
    var _this = this;
    var themeid = e.currentTarget.dataset.themeid;
    var themeContentType = e.currentTarget.dataset.contenttype;
    if (themeContentType == 4 || themeContentType == 5) {
      // 宝贝
      wx.navigateTo({
        url: '../../../../../../interest/pages/interest/theme/goodsDetails/goodsDetails?themeid=' + themeid,
      })
    } else {
      wx.navigateTo({
        url: '../../../../../../interest/pages/interest/theme/themeDetails/themeDetails?themeid=' + themeid,
      })
    }
  },
  circleOperationShow: function () {
    var _this = this;
    _this.setData({
      circleOperationShow: true
    })
  },
  circleOperationClose: function () {
    var _this = this;
    _this.setData({
      circleOperationShow: false
    })
  },
  circleOperationShow2: function () {
    var _this = this;
    _this.setData({
      circleOperationShow2: true,
      circleOperationShow: false,
    })
  },
  circleOperationClose2: function () {
    var _this = this;
    _this.setData({
      circleOperationShow2: false
    })
  },
  navigateToCircleopt: function () {
    var _this = this;
    wx.navigateTo({
      url: '../../editdetails/circleopt/circleopt?circleid=' + circleid,
    })
  },


  /**
   * 退出圈子
   */
  exitCircle: function () {
    var _this = this;
    var joinCount = _this.data.ordInterestJoinCount;
    var identityType = _this.data.thisInterestJoinUser.identityType;
    if (identityType == 1 && joinCount > 1) {
      // 圈主并且还是有其他成员的
      _this.setData({
        exitCircleDialogShow: true,
        circleOperationShow: false
      })
    } else {
      _this.setData({
        exitCircleDialogShow2: true,
        circleOperationShow: false
      })
    }
  },

  /**
   * 圈主退出圈子弹窗：取消动作
   */
  exitCircleDialogClose: function () {
    var _this = this;
    _this.setData({
      exitCircleDialogShow: false,
    })
  },

  /**
   * 圈主退出圈子弹窗：确认动作
   */
  exitCircleDialogSuccess: function () {
    var _this = this;
    var circleid = _this.data.interestJoinCircle.circleid;
    _this.setData({
      exitCircleDialogShow: false,
    })
  },

  /**
   * 用户退出圈子弹窗：取消动作
   */
  exitCircleDialogClose2: function () {
    var _this = this;
    _this.setData({
      exitCircleDialogShow2: false,
    })
  },

  /**
   * 用户退出圈子弹窗：确认动作
   */
  exitCircleDialogSuccess2: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        data.id = _this.data.circleid;
        util.post(api.Home_ExitCircleApiUrl, data).then(function (res) {
          if (res.code == 200) {
            _this.exitCircleDialogClose2();
            util.showToast("退出圈子成功", "success");
            _this.redirectToHome()
          } else {
            util.showToast(res.message, "none");
          }
        })
      })
    }
  },

  /**
   *  开通店铺弹窗
   */
  preferentialOpenStoreDialogShow: function () {
    var _this = this;
    _this.setData({
      preferentialOpenStoreDialogShow: true,
      openStoreDialogShow: false
    })
  },

  /**
   * 圈子分销
   */
  circleDistribution: function (e) {
    // 未开通店铺弹窗，进行弹窗
    var _this = this;
    var type = e.target.dataset.type;
    var circleid = _this.data.circleid;
    // 校验当前用户是否有开通店铺
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var param = {};
        param.access_token = res.access_token;
        param.openid = openid;
        param.circleid = circleid;
        util.post(api.My_checkUserOpenStoreApi, param).then(function (res2) {
          if (res2.code == 200) {
            var obj = res2.result.obj;
            if (!obj.isOpen) {
              // 未开通
              var openStorePrice = obj.openStorePrice;// 开通原价
              var storePreferentialPrice = obj.storePreferentialPrice;
              var preferentialPrice = storePreferentialPrice.preferentialPrice;// 开通优惠价格
              var openText = "";
              var openPrice = 0;
              var openType = 1;
              if (preferentialPrice > 0 && preferentialPrice < openStorePrice) {
                openText = "优惠";
                openType = 1;
                openPrice = openStorePrice - preferentialPrice;
              } else if (preferentialPrice > 0 && preferentialPrice == openStorePrice) {
                openText = "免费";
                openType = 2;
                openPrice = 0;
              } else {
                openText = "";
                openPrice = openStorePrice;
                openType = 3;
              }
              obj.openText = openText;
              obj.openPrice = openPrice;
              obj.openType = openType;
              _this.setData({
                openStoreInfo: obj
              })
              _this.openStoreDialogShow();
            } else {
              if (type == 1) {
                // 进入店铺
                wx.navigateTo({
                  url: '../../../../../../grade/pages/grade/myStore/myStore?openid=' + _this.data.mainUser.openid,
                })
              } else {
                var distributionCount = obj.distributionCount;
                if (distributionCount <= 0) {
                  // 未加入分销
                  _this.joinCommissionShow();
                } else {
                  var distributionDetails = obj.distributionDetails;
                  var shareImage = distributionDetails.shareImageIp + distributionDetails.shareImageUrl;
                  _this.setData({
                    ["shareInfo.circleid"]: circleid,
                    ["shareInfo.shareImage"]: shareImage,
                    ["shareInfo.shareImageDialogShow"]: true
                  })
                }
              }
            }
          }
        })
      });
    }
  },

  /**
   * 加入店铺弹窗
   */
  joinCommissionShow: function () {
    var _this = this;
    _this.setData({
      joinCommissionShow: true
    })
  },

  /**
   *  未开通店铺弹窗
   */
  openStoreDialogShow: function () {
    var _this = this;
    _this.setData({
      openStoreDialogShow: true
    })
  },

  /**
   *  开通店铺弹窗关闭
   */
  preferentialOpenStoreDialogClose: function () {
    var _this = this;
    _this.setData({
      preferentialOpenStoreDialogShow: false,
      storeDialogShowIndex: "",
      openStoreInfo: {}
    })
  },

  /**
   * 开通店铺
   */
  preferentialOpenStoreDialogSuccess: function () {
    var _this = this;
    var openStoreInfo = _this.data.openStoreInfo;
    var openStorePrice = openStoreInfo.openStorePrice;// 开通原价
    var preferentialPrice = openStoreInfo.storePreferentialPrice.preferentialPrice;// 开通优惠价格
    var payStorePrice = openStorePrice - preferentialPrice;// 需要支付的金额
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      wx.showLoading({
        title: '开通店铺中',
      })
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var param = {};
        param.access_token = res.access_token;
        param.payStorePrice = payStorePrice;// 用于校验页面展示金额是否和实际支付金额一致
        param.openid = openid;
        util.post(api.My_openStoreApi, param).then(function (res2) {
          if (res2.code == 200) {
            var buyJoinState = res2.result.buyJoinState;
            var json = res2.result.obj;
            var orderNum = json.orderNum;
            var totalMoney = json.totalMoney;
            if (buyJoinState == 1) {
              // 不需要支付
              util.showToast("开通店铺成功~", "success");
              _this.preferentialOpenStoreDialogClose();
            } else {
              // 需要调用微信支付
              _this.wechatCallbackBusiness(orderNum, totalMoney);
            }
          } else {
            util.showToast(res2.message, "none");
          }
          wx.hideLoading();
        })
      });
    }
  },

  /**
   * 微信支付回调：这个应该是支付后自动触发，但是开发阶段，就代码触发
   */
  wechatCallbackBusiness: function (orderNum, totalMoney) {
    var _this = this;
    var param = {};
    param.orderNum = orderNum;
    param.actualPrice = totalMoney;
    param.outTradeNo = new Date().getTime();
    util.post(api.Interest_WechatCallback, param, "application/x-www-form-urlencoded;charset=UTF-8").then(function (res) {
      wx.showLoading({
        title: '支付中',
      })
      getOrderByOrderNumInterval = setInterval(function () {
        _this.getOrderByOrderNum(orderNum);
      }, 1000);
    })
  },

  /**
   * 加入店铺弹窗关闭
   */
  joinCommissionClose: function () {
    var _this = this;
    _this.setData({
      joinCommissionShow: false
    })
  },

  /**
   * 确定分销
   */
  joinCommissionSuccess: function () {
    var _this = this;
    var circleid = _this.data.circleid;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      wx.showLoading({
        title: '提交中',
      })
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var param = {};
        param.openid = openid;
        param.circleid = circleid;
        param.access_token = res.access_token;
        param.commissionJoinType = 1;
        util.post(api.Interest_joinCommissionInterest, param).then(function (res2) {
          wx.hideLoading();
          if (res2.code == 200) {
            var obj = res2.result.obj;
            _this.setData({
              ["shareInfo.circleid"]: circleid,
              ["shareInfo.shareImage"]: obj,
              ["shareInfo.shareImageDialogShow"]: true
            })
            _this.joinCommissionClose();
          } else {
            util.showToast(res2.message, "none");
          }
        })
      });
    }
  },

  /**
   * 关闭分销的分享图片
   */
  shareImageDialogClose: function () {
    var _this = this;
    util.showToast("此分销项目已入驻你的店铺，请及时推广分享", "none");
    _this.setData({
      shareInfo: { "shareImageDialogShow": false, "shareImage": "", "circleid": "" }
    })
  },


  /**
   * 保存图片到相册
   */
  onSavePicClick: function (e) {
    var _this = this;
    var downloadUrl = e.target.dataset.path;
    // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.writePhotosAlbum" 这个 scope  
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.writePhotosAlbum'] == false) {
          // 没有授权《保存图片》权限
          _this.setData({
            photoDialogShow: true
          })
        } else {
          //已经授权《保存图片》权限
          util.downloadImage(downloadUrl);
        }
      },
      fail(res) {
      }
    })
  },

  /**
   * 关闭没有授权《保存图片》弹窗
   */
  photoDialogClose: function () {
    var _this = this;
    _this.setData({
      photoDialogShow: false
    })
  },

  /**
   * 《保存图片》未授权的弹窗确认动作
   */
  photoDialogSuccess: function (e) {
    var _this = this;
    var downloadUrl = e.target.dataset.path;
    wx.openSetting({
      success: function (data) {
        if (data.authSetting["scope.writePhotosAlbum"] == true) {
          // 授权成功
          _this.photoDialogClose();
          util.downloadImage(downloadUrl)
        } else {
          // 授权失败
          _this.photoDialogClose();
        }
      }
    })
  },
})